23 design patterns (a) - assembly collaborative model

A typical three components cooperative mode

Template Method: Template Method Pattern

In the software build process for a task, often have a stable overall operating structure, but there are a lot of various sub-steps of changing needs, or can not be achieved at the same time due to the overall structure and tasks inherent.

Definition of a skeleton of an algorithm, say some steps (varying) delay to subclasses, subclasses can be multiplexed in a configuration algorithm (backbone) and redefine (Overwrite) certain steps

eg1:不使用Template Method
public class TemplateMethod {
    public boolean stap2() {
        return false;
    }

    public void stap4() {
    }

    public void run() {
        TemplateMethod templateMethod = new TemplateMethod();
        Lib lib = new Lib();
        try {
            lib.stap1();
            if (templateMethod.stap2()) {
                lib.stap3();
            } else {
                templateMethod.stap4();
            }
            lib.stap5();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Lib {
    public void stap1() {
    }

    public boolean stap3() {
        return false;
    }

    public void stap5() {
    }
}

Drawbacks: TemplateMethod To implement run()、 stap2() 、stap4()the method, however, run () in this case, a relatively stable block, belonging to the skeleton of the algorithm. Belonging to the subclass call the parent class method (early binding)

eg2:使用Template Method
public class TemplateMethod2 extends Lib2 {

    @Override
    public boolean stap2() {//变化点
        return false;
    }

    @Override
    public void stap5() {//变化点
    }

    public static void main(String[] args) {
        Lib2 templateMethod2 = new TemplateMethod2();
        templateMethod2.run();
    }
}

abstract class Lib2 {
    public void stap1() {
    }

    public abstract boolean stap2();// 声明为抽象方法

    public boolean stap3() {
        return false;
    }

    public void stap4() {
    }

    public abstract void stap5(); // 声明为抽象方法

    public void run() {  //稳定骨架(模板)
        try {
            stap1();
            if (stap2()) {
                stap3();
            } else {
                stap4();
            }
            stap5();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Advantages: TemplateMethod2 To implement stap2() 、stap4()the method, however, run () in this case, a relatively stable block, belongs to the backbone of the algorithm has been implemented in the parent class. Belong to a subclass method calls the parent class (late binding).

Template Method pattern class diagram .png

Strategy: Strategy Mode

In the software build process, some objects using a variety of algorithms may frequently change, if these algorithms are coded into objects, so that the object will become very complex; and sometimes not support algorithm is also used in a performance burden.

Define a series of algorithms, encapsulate them one by one, and that they can replace each (variation). This mode allows the algorithm may be independent clients that use it (stable) varied (extended, subclass).

//策略接口
public interface Strategy {
    //定义的抽象算法方法 来约束具体的算法实现方法
    public void algorithmMethod();
}

// 具体的策略实现1
class ConcreteStrategy1 implements Strategy {
    //具体的算法实现
    @Override
    public void algorithmMethod() {
        System.out.println("ConcreteStrategy1");
    }
}

// 具体的策略实现2
class ConcreteStrategy2 implements Strategy {
    //具体的算法实现
    @Override
    public void algorithmMethod() {
        System.out.println("ConcreteStrategy2");
    }
}

//策略上下文
class StrategyContext {
    private Strategy strategy;//持有一个策略实现的引用

    public StrategyContext(Strategy strategy) { //使用构造器注入具体的策略类
        this.strategy = strategy;
    }

    public void contextMethod() {
        strategy.algorithmMethod(); //调用策略实现的方法
    }
}

class Client {
    public static void main(String[] args) {
        Strategy concreteStrategy1 = new ConcreteStrategy1(); //创建具体测策略实现
        StrategyContext strategyContext = new StrategyContext(concreteStrategy1); //在创建策略上下文的同时,将具体的策略实现对象注入到策略上下文当中
        strategyContext.contextMethod(); //调用上下文对象的方法来完成对具体策略实现的回调
    }
}

Strategy Mode (Strategy) class diagrams .png

  1. Policy Interface role IStrategy: a series of specific strategies used to constrain the algorithm, the policy context of the role ConcreteStrategy use this strategy interfaces to invoke algorithm specific strategies implemented.

  2. Specific policy implementation role ConcreteStrategy: specific strategies to achieve that specific algorithm.

  3. Policy context role StrategyContext: policy context, responsibility and specific strategies interact, generally the policy context object will hold a real strategy to achieve the object, the policy context also allows specific strategies to achieve access to relevant data from which the callback policy context object method.

  1. Strategy is to model each embodied equal to abstract class encapsulating an independent algorithm and interact through the context classes and specific algorithm.
  2. Each policy algorithm are equal, the status is the same, precisely because of the equality of each algorithm, they can mutually is replaced by the.
  3. Although we can dynamically switch each policy, but the same time can use only one strategy .

Observer / Event: Event Mode

One kind among many defining the object ( change object dependency relationship) so that when an object (the Subject) changes state, all of which are dependent on and automatically update notification until

/**
 * @author lillcol
 * 2019/6/13-23:38
 */
//被观察者抽象类
public abstract class Subject {
    abstract void attack(Observer observer);//添加观察者

    abstract void dettack(Observer observer);//移除观察者

    abstract void notifyObserver();//通知观察者

    abstract void operation();//被观察者状态变化
}

//被观察者抽象类
abstract class AbstractSubject extends Subject {
    private List<Observer> observerList = new ArrayList<>(); //观察者对象集合

    @Override
    void attack(Observer observer) {//添加观察者
        observerList.add(observer);
    }

    @Override
    void dettack(Observer observer) {//移除观察者
        observerList.remove(observer);
    }

    @Override
    void notifyObserver() {
        for (Observer observer : observerList) {
            observer.update();
        }
    }
}

//被观察者实现类
class ConcreteSubject extends AbstractSubject {
    @Override
    void operation() {
        System.out.println("ConcreteSubject 要搞事情了");
        notifyObserver();   // 通知所有观察者
    }
}

//观察者抽象类
abstract class Observer {
    public String name;
    abstract void setName(String name);//设置名字

    abstract String getName();//获取名字

    abstract void update();//观察者更新方法
}

class ConcreteObserver1 extends Observer{

    @Override
    void setName(String name) {
        this.name=name;
    }

    @Override
    String getName() {
        return this.name;
    }

    @Override
    void update() {
        System.out.println("伞兵一号 ConcreteObserver1 准备就绪");
    }
}

class ConcreteObserver2 extends Observer{

    @Override
    void setName(String name) {
        this.name=name;
    }

    @Override
    String getName() {
        return this.name;
    }

    @Override
    void update() {
        System.out.println("伞兵二号 ConcreteObserver2 准备就绪");
    }
}
//测试案例:
class Test{
    public static void main(String[] args) {
        ConcreteSubject concreteSubject = new ConcreteSubject();
        ConcreteObserver1 concreteObserver1 = new ConcreteObserver1();
        ConcreteObserver2 concreteObserver2 = new ConcreteObserver2();
        concreteSubject.attack(concreteObserver1);
        concreteSubject.attack(concreteObserver2);
        concreteSubject.operation();
        System.out.println("------");
        concreteSubject.dettack(concreteObserver1);
        concreteSubject.operation();
    }
}
//输出:
ConcreteSubject 要搞事情了
伞兵一号 ConcreteObserver1 准备就绪
伞兵二号 ConcreteObserver2 准备就绪
------
ConcreteSubject 要搞事情了
伞兵二号 ConcreteObserver2 准备就绪

Observer mode - FIG class .png

In fact, publish-subscribe model, publishers publish information, subscriber access to information;
subscription will be able to receive the information, did not subscribe to receive information.

Reference document: Li Jianzhong - (23 design patterns)
This article original article, in turn please indicate the source! ! ! !

Guess you like

Origin www.cnblogs.com/lillcol/p/11129935.html