设计模式学习(四) 行为型 -1- 模板 命令 责任链 策略 迭代器 中介者

2020年04月29日-

行为型:

  关注对象的行为、研究对象之间的交互。

剩下11种:

  模板方法模式、命令模式、责任链模式、策略模式、迭代器模式、中介者模式、观察者模式、备忘录模式、访问者模式、状态模式、解释器模式

·有点多准备分两部分写· 这一篇写了6个:模板模式 命令模式 责任链模式 策略模式 迭代器模式 中介者模式

#模板方法模式(Template Method Pattern) Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.Template Method lets subclasses redefine certain steps of an algorithm withoutchanging the algorithm's structure

  抽象类中定义一些模板、在子类中按需重构算法的一些步骤

  优点:封装不变的部分、扩展可变的部分、便于维护代码。

  适用:具有类似的逻辑、把相同的部分封装到父类。

  两个角色:

    抽象模板(Abstract Template)角色:定义几个模板方法。

    具体模板(Concrete Template)角色:不同的具体模板可以有不同的实现。

  

   抽象模板:

public abstract class AbstractClass {

    private boolean flag;

    public AbstractClass(boolean flag) {
        this.flag = flag;
    }

    abstract void start();

    abstract void play();

    abstract void end();

    public void run() {
        this.start();
        if (flag) {
            this.play();
        }
        this.end();
    }

}

  具体模板:

public class MethodA extends AbstractClass{

    public MethodA(boolean flag) {
        super(flag);
    }

    void start() {
        System.out.println("methodA start");
    }

    void play() {
        System.out.println("methodA play");
    }

    void end() {
        System.out.println("methodA end");
    }
}

  测试:

 #命令模式(Command Pattern)  Encapsulate a request as an object, thereby letting you parameterize clients withdifferent requests, queue or log requests, and support undoable operations.

  又称为行动(Action)模式或交易(Transaction)模式

   请求封装成的对象

  优点:可扩展性好、低耦合。缺点:可能会有很多具体命令类。

  适用:命令、回调

  四个角色:

    命令(Command)角色:封装具体命令的接口。

    具体命令(Concrete Command)角色:接收者和行为之间的弱耦合

    调用者(Invoker)角色:执行请求

    接收者(Receiver)角色:实施

// 抽象命令
public interface Command {

    void run();
}
// 具体命令
public class ConcreteCommand implements Command {
    private Receiver receiver;

    public ConcreteCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    public void run() {
        receiver.start();
    }
}
// 接收者
public class Receiver {

    public void start(){
        System.out.println("Start System");
    }

}

测试:

 #责任链模式(Chain of Responsibility Pattern) Avoid coupling the sender of a request to its receiver by giving more than one object achance to handle the request. Chain the receiving objects and pass the request alongthe chain until an object handles it.

   重点是在“链”上。请求创建了一个接收者对象的链、使多个对象都有机会处理请求,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。

  简单说就是类似 switch case 或sql 里的 case when

  优点:请求与处理分开、耦合度低、更加灵活。缺点:链过长或导致性能下降、不易调试。

·  适用:多个对象都可以处理一个请求、运行时来决定谁来处理。文件审批。

  两个角色:

    抽象处理者(Handler)角色:抽象类

      具体处理者(Concrete Handler)角色:工作人员

 抽象处理者:

public abstract class Handler {

    private Handler handler;

    public abstract void work(int index);

    // 传递给下一个
    public void next(int index) {
        if (handler != null) {
            handler.work(index);
        } else {
            System.out.println("输入的数值太大 无法处理");
        }
    }

    public Handler(Handler handler) {
        this.handler = handler;
    }

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

}

具体处理者:ABC三个工作人员

public class WorkerA extends Handler {

    public WorkerA(Handler handler) {
        super(handler);
    }

    public void work(int index) {
        if (index < 10) {
            System.out.println("A 处理了该需求");
        } else {
            System.out.println("A 传递给了下一位工作人员");
            next(index);
        }
    }
}
public class WorkerB extends Handler {

    public WorkerB(Handler handler) {
        super(handler);
    }

    public void work(int index) {
        if (index < 20) {
            System.out.println("B 处理了该需求");
        } else {
            System.out.println("B 传递给了下一位工作人员");
            next(index);
        }
    }
}
public class WorkerC extends Handler {

    public WorkerC(Handler handler) {
        super(handler);
    }

    public void work(int index) {
        if (index < 30) {
            System.out.println("C 处理了该需求");
        } else {
            System.out.println("C 传递给了下一位工作人员");
            next(index);
        }
    }

}

测试:

#策略模式(Strategy Pattern) Define a family of algorithms, encapsulate each one, and make them interchangeable.

  也称政策模式。

  类的行为可以在运行时改变。封装算法、可以互换算法。

  即:策略模式是一类算法的通用解决方案,你可以在运行时选择使用哪种方案。

  优点:提供了算法族的行为、公共的方法放到父类、复用性好、容易扩展。缺点:策略类会增多。可以用享元模式减少对象。客户端必须知道所有的策略类的行为都是做什么的。

  三个角色:

    环境(Context)角色:

    抽象策略(Strategy)角色:抽象类或接口

    具体策略(Concrete Strategy)角色:封装算法的类

 

抽象:

// 抽象
public abstract class Strategy {

    private int x;

    private int y;
    // get set
    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
    // 构造
    public Strategy(int x, int y) {
        this.x = x;
        this.y = y;
    }
    // 算法
    public abstract int method();

}

具体:

+:

// 具体
public class StrategyAdd extends Strategy {

    public StrategyAdd(int x, int y) {
        super(x, y);
    }

    public int method() {
        return getX() + getY();
    }

}

-:

public class StrategyMinus extends Strategy {

    public StrategyMinus(int x, int y) {
        super(x, y);
    }

    public int method() {
        return getX() - getY();
    }
}

环境:

// 环境
public class Context {
    private Strategy strategy;

    // 构造
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int getMethod() {
        return strategy.method();
    }
}

测试:

# 迭代器模式(Iterator Pattern)  Provide a way to access the elements of an aggregate object sequentially withoutexposing its underlying representation.

  顺序访问集合对象的元素.不需要知道集合对象的底层表示。

  四个角色:

    抽象迭代器(Iterator)角色:接口

    具体迭代器(Concrete Iterator)角色:实现接口、完成遍历

    抽象聚集(Aggregate)角色:聚合定义迭代器角色对象的接口

    具体聚集(Concrete Aggregate)角色:实现抽象聚集的接口 需要返回的一个迭代器适当的实例。

 抽象迭代器:

public interface Iterator<T> {

     T next();

     boolean hasNext();

}

抽象聚集:

public interface Aggregate<T> {

    void add(T o);

    Iterator createIterator();
}

具体聚集:

public class ConcreteAggregate<T> implements Aggregate<T> {

    private Vector<T> vector = new Vector();// vector类似可变数组

    public void add(T o) {
        vector.add(o);
    }

    public T getAgg(int index) {
        if (index < vector.size()) {
            return vector.get(index);
        } else {
            return null;
        }
    }

    public int size() {
        return vector.size();
    }

    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }

}

具体迭代器:

public class ConcreteIterator<T> implements Iterator<T> {

    private ConcreteAggregate agg;
    private int index = 0;
    private int size = 0;

    // 构造
    public ConcreteIterator(ConcreteAggregate agg) {
        this.agg = agg;
        this.size = agg.size();
        this.index = 0;
    }

    public T next() {
        if (index < size) {
            return (T) agg.getAgg(index++);
        } else {
            return null;
        }
    }

    public boolean hasNext() {
        return index < size;
    }
}

测试:

2020年04月30日-

 #中介者模式(Mediator)Define an object that encapsulates how a set of objects interact. Mediator promotesloose coupling by keeping objects from referring to each other explicitly, and it lets youvary their interaction independently.

   也称调停者模式

  处理不同类之间的交互。

  优点:低耦合(避免同时对象之间过度耦合)、降低复杂度、迪米特原则 缺点:增加了中介者的复杂性、中介者不好复用。

  四个角色:

    抽象中介者(Mediator)角色:统一接口 用于同事之间的交互

    具体中介者(Concrete Mediator)角色:依赖于同事、协调同事之间的关系。

    抽象同事(Colleague)角色:同事的接口

    具体同事(Concrete Colleague)角色:具体同事

 

抽象中介者:

// 中介者
public abstract class Mediator {

    public abstract void  sendMsg(Client client,String msg);

}

具体中介者:

public class ConcreteMediator extends Mediator {

    private ClientA clientA;

    private ClientB clientB;

    public void sendMsg(Client client, String msg) {
        if (client == clientA) {
            clientA.printMsg(clientA.getClass().getName(), msg);
        } else {
            clientB.printMsg(clientB.getClass().getName(), msg);
        }
    }

    public void setClientA(ClientA clientA) {
        this.clientA = clientA;
    }

    public void setClientB(ClientB clientB) {
        this.clientB = clientB;
    }

}

抽象同事:

public abstract class Client {

    private Mediator mediator;

    // 构造
    public Client(Mediator mediator) {
        this.mediator = mediator;
    }

    public Mediator getMediator() {
        return mediator;
    }

    public void setMediator(Mediator mediator) {
        this.mediator = mediator;
    }

    public abstract void sendMsg(String msg);// 由子类实现该方法

    // 共用方法
    public void printMsg(String name, String msg) {
        System.out.println(name + ":" + msg);
    }

}

具体同事:

public class ClientA extends Client {

    public ClientA(Mediator mediator) {
        super(mediator);
    }

    public void sendMsg(String msg){
        getMediator().sendMsg(this,msg);
    }


}

测试:

 总结:

   模板方法模式:把一些步骤延迟到子类中,使得子类可重新定义该算法的某些特定步骤

   命令模式:把请求封装成对象

   责任链模式:请求发送者和接受者之间的解耦。swtch case

   策略模式:把每个算法都封装起来、使他们可以互换。

   迭代器模式:提供容器中访问各个对象的接口。遍历。

   中介者模式:中介对象封装一系列同事对象的交互、同事之间通过中介者交互。

@

-------博客内容仅用于个人学习总结-------
原文地址:https://www.cnblogs.com/DarGi2019/p/12795426.html