这两天快速将设计模式学习了一遍,总结了如下几下:
- Builder模式
Builder模式seperate construction of a complex object from its representation so that the same construction process can create different representation. 将一系列的构造过程封装,在每一步的构造中引入不同的参数,从而使相同的构造步骤产生不同的结果。 -
Adapter模式
Adapter模式Provide an interface for creating families of related or independent objects without specifying their concrete classes. Adapter模式的作用就是接口转换,在不改变原接口的情况下,能够使已有功能复用。
class Adapter extends Shape{
private Ellipse ellipseObj = new Ellipse();
@Override
public void Draw(){
//复用已有的DrawEllipse接口,而不用新建一个类
ellipseObj.DrawEllipse();
}
-
Bridge模式
Bridge模式Decouple an abstraction from its implementation so that the two can vary independently. 将定义与实现解耦,从而使两者能够独立的变化。
Bridge模式中,最关键的步骤是在Abstraction中定义一个AbstractionImpl的对象用于表示实现,当RefinedAbstraction中需要哪种实现,就SetImpl哪种实现。
public static void main(String[] args){
RefineAbstract abstraction = new RefineAbstract();
Implementation implA = new ImplementationA();
Implementation implB = new ImplementationB();
abstraction.setImpl(implA);
abstraction.Operation();
}
-
Decorate模式
Decorate模式 Attach additional responsibilities to an object dynamically keeping the same interface. Decorateprovide a flexible alternative to subclass for extending functionally. 动态地给一个对象添加一些额外的职责。就增加的功能来说,装饰模式相比生成子类更为灵活。该种模式适用于给已有类添加新的功能,但不知道新的功能的实现顺序。
重要的是, 1、Decorate继承了Component,从而使用基类类型与接口,也能实现Decorate功能!2、构造函数使用了Componet对象,从而使一个ConcreteDecorator能够初始化另外一个ConcreteDecorate,实现了功能顺序的任意调换!
public class MyFileSys {
public static void main(String[] args) {
FileSys fileSys = new StandardFileSys();//可以随意调换Rar与Encrypt的顺序
FileSys rarFileSys = new RarFileSys(fileSys);
FileSys encryptFileSys = new EncryptFileSys(rarFileSys);//使用的是基类类型与定义的指针,实现的是Decorate类的功能。
encryptFileSys.Operation();
}
}
abstract class FileSys{
abstract public void Operation();
}
class StandardFileSys extends FileSys {
@Override
public void Operation(){
System.out.println("New a FileSys");
}
}
//Decorate类继承Component类,从而使用基类类型与定义好的接口,就能实现Decorate类的功能。
class DecorateFileSys extends FileSys{
//使用组合类型
protected FileSys fileSys;
public DecorateFileSys(FileSys fileSys) {
this.fileSys = fileSys;
}
@Override
public void Operation(){
fileSys.Operation();
}
}
class EncryptFileSys extends DecorateFileSys{
public EncryptFileSys(FileSys fileSys) {
super(fileSys);
}
@Override
public void Operation(){
super.Operation();
Encrypt();
}
}
- Composite模式
Composite模式Compose objectsinto tree structure to represent part-whole hierarchies. Composite lets clientstreat individual objects and compositions of object uniformly.将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
想想文件夹 -
Facede模式
Façade模式 Provide a unified interface to a set of interface in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use. 要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行。门面模式提供了一个高层次的接口,使得子系统更容易使用。
Façade模式面对的往往是多个类或其他程序单元,通过重新组合各类及程序单元,对外提供统一的接口/界面。
public class CarFacade{
public static void main(String[] args){
int[] flags = new int[]{1,2,3,4};
Facade carFacade = new Facade(flags);
carFacade.Run();
carFacade.Stop();
}
}
class Facade{
protected Wheel[] wheel = new Wheel[4];
protected Body body;
public Facade(int[] flags) {
for(int i = 0; i<4; i++){
wheel[i] = new Wheel(flags[i]);
}
body = new Body();
}
public void Stop () {
for(int i = 0; i<4; i++){
wheel[i].Stop();
}
body.Stop();
}
public void Run () {
for(int i = 0; i<4; i++){
wheel[i].Run();
}
body.Run();
}
}
- Template模式
Template模式Define the skeleton of an algorithm in an operation, deferring some steps to subclass. Template Method lets subclass redefine certain steps of an algorithm without changing the algorithm’ structure. 定义一个操作中的算法框架,将一些步骤延迟到子类。使得子类算法可以不改变一个算法的结构即可以重定义该算法的某些特定步骤。
Template模式通过继承,将通用的算法架构抽象成接口,而将算法实现延迟到了子类实现。从而实现了不同的子类,其算法框架是一致的,但算法方法不一致。
DIP(依赖倒置), 由父类定义接口,控制权在父类。将具体实现和抽象接口之间解耦。
abstract class Template {
public void Operation(){
ExecuteStep1();
ExecuteStep2();
}
abstract void ExecuteStep1();
abstract void ExecuteStep2();
}
class ConcreteTemplate1 extends Template{
void ExecuteStep1(){
System.out.println("Execute Step1 of ConcreteTemplate1");
}
void ExecuteStep2(){
System.out.println("Execute Step2 of ConcreteTemplate1");
}
}
public class Client{
public static void main(String[] args){
Template template1 = new ConcreteTemplate1();
template1.Operation();
}
}
- Strategy模式
Strategy模式 Define a family of algorithms, en capsulate each one, and make them interchangeable. 定义一组算法,将每个算法都封装起来,使得他们之间可以互换。
通过组合,Context中存放算法类对象Strategy,不同的Strategy对象,实现不同的算法。
public class Client {
public static void main(String[] args){
Stratery strateryA = new StrageryA();
ContextExample curContext = new ContextExample(strateryA);
curContext.Execute();
}
}
abstract class Stratery{
abstract void Operation();
}
class StrageryA extends Stratery{
@Override
void Operation(){
System.out.println("Execute StrageryA");
}
}
class ContextExample{
Stratery stragery;
public ContextExample(Stratery stratery){
this.stragery = stratery;
}
public void Execute(){
stragery.Operation();
}
}
9.Command模式
Command模式 Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。
调用者,命令,执行者之间的解耦,将命令封装成类,许多系统的消息发送,异步的,就是采用此模式。
public class Client {
public static void main(String[] args){
CommandReceiver commandReceiver = new CommandReceiver();
Command command = new ConcreteCommand(commandReceiver);
Invoke invoke = new Invoke();
invoke.setCommand(command);
invoke.executeCommand();
}
}
//将命令封装成类
abstract class Command{
protected CommandReceiver commondReceiver;
public Command(CommandReceiver commandReceiver){
this.commondReceiver = commandReceiver;
}
abstract void execute();
}
class ConcreteCommand extends Command{
public ConcreteCommand(CommandReceiver commandReceiver){
super(commandReceiver);
}
void execute(){
this.commondReceiver.execute();
}
}
//命令的执行者
class CommandReceiver{
public void execute(){
System.out.println("execute commond");
}
}
//命令的调用者
class Invoke{
protected Command command;
public void setCommand(Command command){
this.command = command;
}
public void executeCommand(){
this.command.execute();
}
}
-
Observer模式
Observer模式Defined a one-to-many dependency between objects so that when one object changes state,all its dependents are notified and update automatically. 定义对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖于它的对象都会得到通知并被自动更新。
public class Client {
public static void main(String[] args){
Subject subject = new ConcreteSubject();//新建观察者时,就把自己加到了被观察者的队列中
ObserverA observerA = new ObserverA(subject);
ObserverB observerB = new ObserverB(subject);//被观察者每更新一次状态,观察者就都收到通知
subject.setState(Subject.OPEN_STATE);
System.out.println();
subject.setState(Subject.CLOSED_STATE);
observerA.detach();
observerB.detach();
}
}
abstract class Subject{
static final int OPEN_STATE = 0;
static final int CLOSED_STATE = 1;
protected int state = CLOSED_STATE;
protected Vector<Observer> observers = new Vector<Observer>();
abstract void attach(Observer observer);
abstract void detach(Observer observer);
abstract void notify();
void setState(int state){
this.state = state;
notify();
}
int getState(){
return state;
}
}
class ConcreteSubject extends Subject{
void attach(Observer observer){
observers.add(observer);
}
void detach(Observer observer){
observers.removeElement(observer);
}
void notify(){
Iterator<Observer> iterator;
for(iterator = observers.iterator(); iterator.hasNext();){
Observer observer = (Observer)iterator.next();
observer.update();
}
}
}
abstract class Observer{
protected Subject subject;
public Observer(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
protected void detach() {
if (subject!=null) {
this.subject.detach(this);
}
}
abstract void update();
}
class ObserverA extends Observer{
public ObserverA(Subject subject) {
super(subject);
}
void update(){
int state = subject.getState();
String outpString = "Subject's state is "+Integer.toString(state)+" from ObserverA";
System.out.println(outpString);
}
}
class ObserverB extends Observer{
public ObserverB(Subject subject) {
super(subject);
}
void update(){
int state = subject.getState();
String outpString = "Subject's state is "+Integer.toString(state)+" from ObserverB";
System.out.println(outpString);
}
}
-
State模式
State模式Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. 当一个对象在状态改变时允许其改变行为,这个对象看起来像改变了其类。
public class Client {
public static void main(String[] args) {
Fire fire = new Fire();
fire.TurnOffFire();
fire.TurnUpFire();
fire.TurnUpFire();
fire.TurnOffFire();
fire.TurnUpFire();
fire.TurnUpFire();
fire.TurnOffFire();
fire.TurnUpFire();
}
}
abstract class FireState {
abstract public void TurnUpFire(Fire fire);
abstract public void TurnOffFire(Fire fire);
}
class Fire{
FireState fireState;
public Fire() {
fireState = new OffState();
}
public void SetFireState(FireState fireState){
this.fireState = fireState;
}
public FireState GetFireState(){
return fireState;
}
public void TurnUpFire(){
fireState.TurnUpFire(this);
}
public void TurnOffFire(){
fireState.TurnOffFire(this);
}
}
class OffState extends FireState {
public void TurnUpFire(Fire fire) {
fire.SetFireState(new LowState());
System.out.println("已调至小火");
}
public void TurnOffFire(Fire fire) {
System.out.println("火未打着");
}
}
class LowState extends FireState {
public void TurnUpFire(Fire fire) {
fire.SetFireState(new MediumState());
System.out.println("已调至中火");
}
public void TurnOffFire(Fire fire) {
fire.SetFireState(new OffState());
System.out.println("火已熄灭");
}
}
class MediumState extends FireState {
public void TurnUpFire(Fire fire) {
fire.SetFireState(new HighState());
System.out.println("已调至大火");
}
public void TurnOffFire(Fire fire) {
fire.SetFireState(new LowState());
System.out.println("已调至小火");
}
}
class HighState extends FireState {
public void TurnUpFire(Fire fire) {
System.out.println("已是最大火");
}
public void TurnOffFire(Fire fire) {
fire.SetFireState(new MediumState());
System.out.println("已调至中火");
}
}
-
Visitor模式
Visitor模式Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. 封装一些作用于某种数据结构中的各种元素,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。
Visitor双重分派,调用者的动态解析
public class Client {
public static void main(String[] args){
Visitor visitor = new XinAnJiang();
Disaster disaster = new SnowDisaster();
disaster.accept(visitor);
}
}
abstract class Visitor{
abstract public void visit(Disaster disaster);
}
class XinAnJiang extends Visitor{
@Override
public void visit(Disaster disaster) {
String outString = "XinAnJiang Model Work on "+ disaster.toString();
System.out.println(outString);
}
}
class ShuoMoXing extends Visitor{
@Override
public void visit(Disaster disaster) {
String outString = "ShuoMoXing Model Work on "+ disaster.toString();
System.out.println(outString);
}
}
abstract class Disaster{
protected String name;
public void accept(Visitor visitor){
visitor.visit(this);
}
}
class SnowDisaster extends Disaster{
@Override
public String toString() {
return "SnowDisster";
}
}
class FireDisaster extends Disaster{
@Override
public String toString(){
return "FireDisaster";
}
}
网友评论