行为型设计模式

199 阅读4分钟

前言

行为设计模式有11种,比较多,策略模式,模板方法模式,观察者模式,迭代器模式,责任链模式,命令模式,备忘录模式,状态模式,访问者模式,中介者模式,解释器模式11种,还是比较多的,下面一一介绍一下每种设计模式定义和使用场景。

image.png

1. 策略模式

1.1 定义

策略模式(Strategy Pattern)

Define a family of algorithms, encapsulate each one, and make them interchangeable.

定义一组算法, 将每个算法都封装起来, 并且使他们之间可以互换.

1.2 使用场景

  • Context 上下文角色
  • Strategy 抽象策略角色
  • ConcreteStrategy 具体策略角色

image.png

伪代码:

public class Client {

    public static void main(String[] args) {
        Strategy strategy = new ConcreteStrategy1();
        Context context = new Context(strategy);
        context.doAnyThing();
    }
}

// 抽象接口
public interface Strategy {
    public void doSomething();
}

// 上下文
public class Context {

    private Strategy strategy = null;
    public  Context (Strategy strategy) {
        this.strategy = strategy;
    }

    public void doAnyThing() {
        this.strategy.doSomething();
    }
}

// 策略1
public class ConcreteStrategy1 implements Strategy {
    @Override
    public void doSomething() {

    }
}
// 策略2
public class ConcreteStrategy2 implements Strategy {
    @Override
    public void doSomething() {
        
    }
}

2. 模板方法模式

2.1 定义

模板方法模式(Template 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 without changing the algorithm's structure.

定义一个操作的算法框架,而将一些步骤延迟到子类中.

2.2 使用场景

  • 实现一些操作时,整体步骤很固定,但是呢。就是其中一小部分需要改变,这时候可以使用模板方法模式,将容易变的部分抽象出来,供子类实现。 image.png

伪代码

public class Client {

    public static void main(String[] args) {
        AbstractClass a = new ConcreteClassA();
        AbstractClass b = new ConcreteClassB();
        a.templateMethod();
        b.templateMethod();
    }
}
// 抽象类模板方法
public abstract class AbstractClass {
    protected abstract void doSomething();

    protected abstract void doAnything();

    public void templateMethod() {
        this.doSomething();
        this.doAnything();
    }
}

// 具体实现类
public class ConcreteClassA extends AbstractClass{
    @Override
    protected void doSomething() {

    }

    @Override
    protected void doAnything() {

    }
}

3. 观察者模式

3.1 定义

观察者模式(Observer Pattern) 也叫发布订阅模式

Define a one-to-many dependency between objects so that when one objects changes state, all its dependents are notified and updated automatically.

3.2 使用场景


// 被观察者
public abstract class Subject {

    private Vector<Observer> observerVector = new Vector<>();

    public void addObserver(Observer observer) {
        observerVector.add(observer);
    }

    public void delObserver(Observer observer) {
        observerVector.remove(observer);
    }

    public void notifyAllObservers() {
        for (Observer observer : observerVector) {
            observer.update();
        }
    }
}

// 观察者
public interface Observer {

    public void update();
}

// 具体被观察者
public class ConcreteSubject extends Subject {

    public void doSomething() {
        super.notifyAllObservers();
    }
}

// 具体观察者
public class ConcreteObserver implements Observer {
    @Override
    public void update() {
        // 具体更新的逻辑
    }
}

4. 迭代器模式

4.1 定义

迭代器模式(Iterator Pattern)

4.2 使用场景

image.png

5. 责任链模式

5.1 定义

责任链模式(Chain Of Responsibility Design Pattern)

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

将请求的发送和接收解耦,让多个接收对象都有机会处理这个请求。将这些接收对象串成一条链,并沿着这条链传递这个请求,直到链上的某个接收对象能够处理它为止。

6. 命令模式

6.1 定义

命令模式(Command Design Pattern)

The command pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations.

命令模式将请求(命令)封装为一个对象,这样可以使用不同的请求参数化其他对象(将不 同请求依赖注入到其他对象),并且能够支持请求(命令)的排队执行、记录日志、撤销等 (附加控制)功能。

7. 备忘录模式

7.1 定义

备忘录模式,也叫快照(Snapshot)模式

Captures and externalizes an object’s internal state so that it can be restored later, all without violating encapsulation.

在不违背封装原则的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便之后恢复对象为先前的状态。

8. 状态模式

8.1 定义

状态模式

Allow an object to alter its behavior when its internal state changes.The object will appear to change its class.

当一个对象内在状态改变时允许其改变行为,这个对象看起来像改变了他的类。

9. 访问者模式

9.1 定义

访问者模式(Visitor Pattern)

Represent an operation to be performed on the elements of an object structure. Vistor lets you define a new operation without changing the classes of the elements on which it operates.

封装一些作用于某种数据结构中的各种元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新操作。

10. 中介者模式

10.1 定义

中介模式(Mediator Design Pattern)

Mediator pattern defines a separate (mediator) object that encapsulates the interaction between a set of objects and the objects delegate their interaction to a mediator object instead of interacting with each other directly.

中介模式定义了一个单独的(中介)对象,来封装一组对象之间的交互。将这组对象之间的交互委派给与中介对象交互,来避免对象之间的直接交互。

11. 解释器模式

11.1 定义

解释器模式(Interpreter Design Pattern)

Interpreter pattern is used to defines a grammatical representation for a language and provides an interpreter to deal with this grammar.

解释器模式为某个语言定义它的语法(或者叫文法)表示,并定义一个解释器用来处理这个语法。