23种 设计模式 详解

背景

在面试、软件设计师等考试、代码分析设计时会有此类需求,因此整理一下。

1、模式分类介绍

1.1、区分

  • 创建型模式主要关注如何创建对象。(巧记:抽工单建原)
  • 行为型模式主要关注对象间如何交互。(巧记:观察策略,迭代模板,责任不推脱。中介访问备忘录,解释命令状态)
  • 结构型模式主要关注如何组织对象。(巧记:适桥组装外享代
1.1.1、创建型模式(Creational Patterns)

创建型模式关注于对象的创建过程,试图以合适的方式创建对象。这些模式提供了一种将对象创建与其使用分离的方法,增加了程序的灵活性和可扩展性。

常见的创建型模式包括:(巧记:抽工单建原)

  1. 单例模式(Singleton):确保一个类只有一个实例,并提供一个全局访问点。
  2. 工厂方法模式(Factory Method):定义一个用于创建对象的接口,让子类决定实例化哪一个类。让工厂接口的子类具体工厂,直接选择new某个具体产品实例。
  3. 抽象工厂模式(Abstract Factory):创建相关或依赖对象的家族,而不需明确指定具体类。
  4. 建造者模式(Builder):构建一个复杂的对象,并允许按步骤构造。
  5. 原型模式(Prototype):通过拷贝现有的实例创建新的实例,而不是通过新建。
1.1.2、行为型模式(Behavioral Patterns)

行为型模式专注于对象间的通信,即对象间如何相互作用以及怎样分配职责。

常见的行为型模式包括:(巧记:观察策略,迭代模板,责任不推脱。中介访问备忘录,解释命令状态)

  1. 观察者模式(Observer):定义了对象间的一种一对多的依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。
  2. 策略模式(Strategy):定义了一系列算法,并将每一个算法封装起来,使它们可以互换,算法的变化不会影响到使用算法的客户。
  3. 迭代器模式(Iterator):提供一种顺序访问聚合对象中的元素的方法,不暴露其内部的表示。
  4. 模板方法模式(Template Method):在一个方法中定义算法的骨架,将一些步骤的执行延迟到子类中。
  5. 责任链模式(Chain of Responsibility):允许将请求沿着链式结构传递,直到有一个对象处理它。
  6. 中介者模式(Mediator):定义了一个简化复杂系统交互的中介对象,以减少对象间的相互依赖。
  7. 访问者模式(Visitor):表示一个作用于某对象结构中的各元素的操作,它使你可以对一个对象结构加以操作,而无需改变结构中的对象类。
  8. 备忘录模式(Memento):允许对象在不破坏封装性的前提下,获取其内部状态的快照,并在需要时恢复到该状态。
  9. 解释器模式(Interpreter):定义了一个语言的语法表示,并且解释这个语言中的句子。
  10. 命令模式(Command):将请求或操作封装为一个对象,允许用户对操作进行参数化、队列处理、或者延迟执行。
  11. 状态模式(State):允许对象在其内部状态改变时改变它的行为,看起来好像改变了其类。
1.1.3、结构型模式(Structural Patterns)

结构型模式主要关注对象的组合,即如何将对象组合成更大的结构以及如何定义它们之间的相互关系。

常见的结构型模式包括:(巧记:适桥组装外享代

  1. 适配器模式(Adapter):允许对象间的接口不兼容的问题,通过一个中间层来转换接口。
  2. 装饰器模式(Decorator):动态地给一个对象添加额外的职责。
  3. 代理模式(Proxy):为其他对象提供一个代替或占位符以控制对它的访问。
  4. 外观模式(Facade):为子系统中的一组接口提供一个一致的界面。
  5. 桥接模式(Bridge):将抽象部分与其实现部分分离,使它们可以独立地变化。
  6. 组合模式(Composite):将对象组合成树形结构以表示“部分-整体”的层次结构。
  7. 享元模式(Flyweight):通过共享来高效地支持大量细粒度的对象。

2、创建型模式

单例模式(Singleton)

public class Singleton {
    // 私有静态变量,保存类的唯一实例
    private static Singleton instance;
  
    // 私有构造函数,防止外部通过new创建对象
    private Singleton() {}
  
    // 公有静态方法,提供全局访问点,返回类的唯一实例
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton(); // 如果实例不存在,则创建一个实例
        }
        return instance; // 返回类的唯一实例
    }
}

工厂方法模式(Factory Method)

// 产品接口
interface Product {
    void use();
}

// 具体产品
class ConcreteProduct implements Product {
    public void use() {
        System.out.println("ConcreteProduct is being used.");
    }
}

// 工厂接口
abstract class Creator {
    // 声明创建产品的抽象方法
    abstract Product factoryMethod();
}

// 具体工厂
class ConcreteCreator extends Creator {
    // 实现创建具体产品的方法
    public Product factoryMethod() {
        return new ConcreteProduct(); // 返回具体产品的实例
    }
}

抽象工厂模式(Abstract Factory)

// 产品A的接口
interface ProductA {
    void useA();
}

// 产品B的接口
interface ProductB {
    void useB();
}

// 具体产品A
class LightProductA implements ProductA {
    public void useA() {
        System.out.println("ConcreteProductA is being used.");
    }
}

// 具体产品B
class LightProductB implements ProductB {
    public void useB() {
        System.out.println("ConcreteProductB is being used.");
    }
}

// 抽象工厂接口
abstract class AbstractFactory {
    abstract ProductA createButton();
    abstract ProductB createText();
}

// 具体工厂
class ConcreteFactory extends AbstractFactory {
    public ProductA createButton() {
        return new LightProductA(); // 创建产品A的实例
    }
  
    public ProductB createText() {
        return new LightProductB(); // 创建产品B的实例
    }
}

==========
android实例
==========
// UI组件接口
interface UIButton {
    void draw();
}

interface UITextField {
    void draw();
}

// 具体UI组件
class LightUIButton implements UIButton {
    public void draw() {
        // 绘制浅色主题的按钮
    }
}

class LightUITextField implements UITextField {
    public void draw() {
        // 绘制浅色主题的文本框
    }
}

// 抽象工厂接口
interface ThemeFactory {
    UIButton createButton();
    UITextField createTextField();
}

// 具体工厂
class LightThemeFactory implements ThemeFactory {
    public UIButton createButton() {
        return new LightUIButton();
    }

    public UITextField createTextField() {
        return new LightUITextField();
    }
}

// 客户端代码
class UIThemeApp {
    private ThemeFactory themeFactory;

    public UIThemeApp(ThemeFactory themeFactory) {
        this.themeFactory = themeFactory;
    }

    public void buildUI() {
        UIButton button = themeFactory.createButton();
        UITextField textField = themeFactory.createTextField();
        button.draw();
        textField.draw();
    }
}

// 使用示例
public class AbstractFactoryDemo {
    public static void main(String[] args) {
        ThemeFactory lightThemeFactory = new LightThemeFactory();
        UIThemeApp app = new UIThemeApp(lightThemeFactory);
        app.buildUI();
    }
}

建造者模式(Builder)

// 产品类
class Product {
    private List<String> parts = new ArrayList<>();
  
    public void add(String part) {
        parts.add(part);
    }
  
    @Override
    public String toString() {
        return "Product{" + "parts=" + parts + '}';
    }
}

// 建造者接口
interface Builder {
    void buildPart1();
    void buildPart2();
    Product getResult();
}

// 具体建造者
class ConcreteBuilder implements Builder {
    private Product product = new Product();
  
    public void buildPart1() {
        product.add("Part1");
    }
  
    public void buildPart2() {
        product.add("Part2");
    }
  
    public Product getResult() {
        return product;
    }
}

// 指挥者
class Director {
    public void construct(Builder builder) {
        builder.buildPart1();
        builder.buildPart2();
    }
}

原型模式(Prototype)

// 产品接口
interface Prototype {

    Prototype clone();
}

// 具体产品
class ConcretePrototype implements Prototype, Cloneable {
    private String id;
  
    public ConcretePrototype(String id) {
        this.id = id;
    }
  
    public String getId() {
        return id;
    }
  
    public void setId(String id) {
        this.id = id;
    }
  
    // 实现克隆方法
    public Prototype clone() {
        try {
            return (ConcretePrototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

// 客户端代码
class Client {
    public static void main(String[] args) {
        ConcretePrototype original = new ConcretePrototype("Original");
        ConcretePrototype cloned = original.clone();
        System.out.println("Original: " + original.getId());
        System.out.println("Cloned: " + cloned.getId());
    }
}

3、行为型模式

策略模式(Strategy)

// 策略接口,定义了所有支持的算法的公共接口
interface Strategy {
    void algorithmInterface();
}

// 具体策略A,实现了策略接口
class ConcreteStrategyA implements Strategy {
    public void algorithmInterface() {
        System.out.println("Algorithm of ConcreteStrategyA is executed");
    }
}

// 具体策略B,也实现了策略接口
class ConcreteStrategyB implements Strategy {
    public void algorithmInterface() {
        System.out.println("Algorithm of ConcreteStrategyB is executed");
    }
}

// 上下文,使用策略接口来调用具体策略的算法
class Context {
    private Strategy strategy;
  
    // 构造函数,传入策略对象
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }
  
    // 可以设置新的策略
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
  
    // 执行策略的方法
    public void executeStrategy() {
        strategy.algorithmInterface();
    }
}

// 客户端代码
public class StrategyPatternDemo {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStrategyA()); // 使用策略A
        context.executeStrategy(); // 执行策略A的算法
  
        context.setStrategy(new ConcreteStrategyB()); // 更换为策略B
        context.executeStrategy(); // 执行策略B的算法
    }
}

模板方法模式(Template Method)

// 抽象类,定义算法的模板
abstract class AbstractClass {
    // 模板方法,定义算法的骨架
    public final void templateMethod() {
        baseOperation1();
        baseOperation2();
        concreteOperation();
    }
  
    // 基本操作1,由子类实现
    public abstract void baseOperation1();
  
    // 基本操作2,由子类实现
    public abstract void baseOperation2();
  
    // 具体操作,由子类实现
    public void concreteOperation() {
        System.out.println("AbstractClass concreteOperation");
    }
}

// 具体类,继承自抽象类并实现抽象方法
class ConcreteClass extends AbstractClass {
    public void baseOperation1() {
        System.out.println("ConcreteClass baseOperation1");
    }
  
    public void baseOperation2() {
        System.out.println("ConcreteClass baseOperation2");
    }
  
    // 重写具体操作
    @Override
    public void concreteOperation() {
        System.out.println("ConcreteClass concreteOperation");
    }
}

// 客户端代码
public class TemplateMethodPatternDemo {
    public static void main(String[] args) {
        ConcreteClass concreteClass = new ConcreteClass();
        concreteClass.templateMethod();
    }
}

观察者模式(Observer)

// 观察者接口
interface Observer {
    void update(String message);
}

// 具体观察者
class ConcreteObserver implements Observer {
    private String name;
  
    public ConcreteObserver(String name) {
        this.name = name;
    }
  
    public void update(String message) {
        System.out.println(name + " : " + message);
    }
}

// 主题接口
interface Subject {
    void registerObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers();
}

// 具体主题
class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String state;
  
    public void registerObserver(Observer o) {
        observers.add(o);
    }
  
    public void removeObserver(Observer o) {
        observers.remove(o);
    }
  
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(state);
        }
    }
  
    public void setState(String state) {
        this.state = state;
        notifyObservers();
    }
  
    public String getState() {
        return state;
    }
}

// 客户端代码
public class ObserverPatternDemo {
    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject();
  
        Observer observer1 = new ConcreteObserver("Observer1");
        Observer observer2 = new ConcreteObserver("Observer2");
  
        subject.registerObserver(observer1);
        subject.registerObserver(observer2);
  
        subject.setState("All observers are notified");
    }
}

迭代器模式(Iterator)

// 聚合接口
interface Aggregate {
    Iterator createIterator();
}

// 具体聚合
class ConcreteAggregate implements Aggregate {
    private List items = new ArrayList();
  
    public void addItem(Object item) {
        items.add(item);
    }
  
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }
  
    // ... 其他方法 ...
}

// 迭代器接口
interface Iterator {
    boolean hasNext();
    Object next();
}

// 具体迭代器
class ConcreteIterator implements Iterator {
    private ConcreteAggregate aggregate;
    private int currentIndex = 0;
  
    public ConcreteIterator(ConcreteAggregate aggregate) {
        this.aggregate = aggregate;
    }
  
    public boolean hasNext() {
        return currentIndex < aggregate.items.size();
    }
  
    public Object next() {
        Object item = aggregate.items.get(currentIndex);
        currentIndex++;
        return item;
    }
  
    // ... 其他方法 ...
}

// 客户端代码
public class IteratorPatternDemo {
    public static void main(String[] args) {
        ConcreteAggregate aggregate = new ConcreteAggregate();
        aggregate.addItem("Item1");
        aggregate.addItem("Item2");
        aggregate.addItem("Item3");
  
        Iterator iterator = aggregate.createIterator();
  
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
============================================================
假设我们要实现一个简单的书店系统,该系统可以列出所有书籍的信息:
============================================================
// 聚合接口
interface Aggregate {
    Iterator createIterator();
}

// 具体聚合类,书店中的书架
class BookShelf implements Aggregate {
    private List<Book> books = new ArrayList<>();

    public void addBook(Book book) {
        books.add(book);
    }

    public Iterator createIterator() {
        return new BookIterator(this); //this 在这里代表 BookShelf 类的一个实例,它将作为参数传递给 BookIterator 的构造函数。
    }
}

// 迭代器接口
interface Iterator {
    boolean hasNext();
    Book next();
}

// 具体迭代器类
class BookIterator implements Iterator {
    private BookShelf shelf;
    private int currentIndex = 0;

    public BookIterator(BookShelf shelf) {
        this.shelf = shelf;
    }

    public boolean hasNext() {
        return currentIndex < shelf.books.size();
    }

    public Book next() {
        if (hasNext()) {
            return shelf.books.get(currentIndex++);
        }
        return null;
    }
}

// 书籍类
class Book {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    // Getters and setters
}

// 客户端代码
public class BookStoreClient {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf();
        bookShelf.addBook(new Book("Book Title 1", "Author 1"));
        bookShelf.addBook(new Book("Book Title 2", "Author 2"));
        // ... 添加更多书籍

        Iterator iterator = bookShelf.createIterator();
        while (iterator.hasNext()) {
            Book book = iterator.next();
            System.out.println("Title: " + book.title + ", Author: " + book.author);
        }
    }
}
在这个示例中,BookShelf是具体聚合类,它实现了Aggregate接口,并且内部维护了一个Book对象的列表。BookIterator是具体迭代器类,实现了Iterator接口,它能够遍历BookShelf中的所有书籍。

客户端代码通过调用BookShelfcreateIterator()方法来获取一个迭代器对象,然后使用while循环和迭代器的hasNext()next()方法来访问并打印每个书籍的信息。

这个示例展示了迭代器模式如何将集合对象的访问和遍历逻辑从客户端代码中分离出来,使得客户端代码不需要关心集合的具体实现细节。

责任链模式(Chain of Responsibility)

// 请求接口
interface Request {
    int getRequestAmount();
}

// 具体请求
class ConcreteRequest implements Request {
    private int amount;
  
    public ConcreteRequest(int amount) {
        this.amount = amount;
    }
  
    public int getRequestAmount() {
        return amount;
    }
}

// 处理器接口
interface Handler {
    void setNext(Handler next);
    void handleRequest(Request request);
}

// 具体处理器
class ConcreteHandlerA extends Handler {
    private Handler next;
  
    public void setNext(Handler next) {
        this.next = next;
    }
  
    public void handleRequest(Request request) {
        if (next != null && request.getRequestAmount() > 10) {
            next.handleRequest(request);
        } else {
            System.out.println("Handled in Handler A: " + request.getRequestAmount());
        }
    }
}

// 另一个具体处理器
class ConcreteHandlerB extends Handler {
    private Handler next;
  
    public void setNext(Handler next) {
        this.next = next;
    }
  
    public void handleRequest(Request request) {
        if (next != null && request.getRequestAmount() > 20) {
            next.handleRequest(request);
        } else {
            System.out.println("Handled in Handler B: " + request.getRequestAmount());
        }
    }
}

// 客户端代码
public class ChainOfResponsibilityPatternDemo {
    public static void main(String[] args) {
        Handler handlerA = new ConcreteHandlerA();
        Handler handlerB = new ConcreteHandlerB();
  
        handlerA.setNext(handlerB); // 设置责任链
  
        Request request1 = new ConcreteRequest(15);
        Request request2 = new ConcreteRequest(25);
  
        handlerA.handleRequest(request1); // 由handlerB处理
        handlerA.handleRequest(request2); // 由handlerB处理
    }
}

中介者模式(Mediator)

// 定义中介者接口
interface Mediator {
    void createMediator();
    void sendMessage(String message, Colleague colleague);
}

// 创建具体的中介者类
class ConcreteMediator implements Mediator {
    private ColleagueA colleagueA;
    private ColleagueB colleagueB;

    // 在中介者中创建同事对象
    @Override
    public void createMediator() {
        colleagueA = new ColleagueA(this);
        colleagueB = new ColleagueB(this);
    }

    // 发送消息给同事
    @Override
    public void sendMessage(String message, Colleague colleague) {
        if (colleague == colleagueA) {
            colleagueB.receiveMessage(message);
        } else if (colleague == colleagueB) {
            colleagueA.receiveMessage(message);
        }
    }
}

// 定义同事类接口
interface Colleague {
    void receiveMessage(String message);
    void sendMediatorMessage(String message);
}

// 创建具体的同事类A
class ColleagueA implements Colleague {
    private Mediator mediator;

    public ColleagueA(Mediator mediator) {
        this.mediator = mediator;
    }

    @Override
    public void receiveMessage(String message) {
        System.out.println("ColleagueA received message: " + message);
    }

    @Override
    public void sendMediatorMessage(String message) {
        mediator.sendMessage(message, this);
    }
}

// 创建具体的同事类B
class ColleagueB implements Colleague {
    private Mediator mediator;

    public ColleagueB(Mediator mediator) {
        this.mediator = mediator;
    }

    @Override
    public void receiveMessage(String message) {
        System.out.println("ColleagueB received message: " + message);
    }

    @Override
    public void sendMediatorMessage(String message) {
        mediator.sendMessage(message, this);
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Mediator mediator = new ConcreteMediator();
        mediator.createMediator(); // 创建中介者并初始化同事

        ColleagueA colleagueA = (ColleagueA) mediator;
        ColleagueB colleagueB = (ColleagueB) mediator;

        colleagueA.sendMediatorMessage("Hello from A to B");
        colleagueB.sendMediatorMessage("Hello from B to A");
    }
}
/*
代码解释:
Mediator 接口定义了中介者的行为,包括创建中介者和发送消息给同事的方法。
ConcreteMediator 类实现了 Mediator 接口,负责协调各个同事之间的交互。
createMediator() 方法在中介者中创建同事对象 colleagueA 和 colleagueB。
sendMessage() 方法允许一个同事通过中介者向另一个同事发送消息。
Colleague 接口定义了同事的行为,包括接收消息和通过中介者发送消息的方法。
ColleagueA 和 ColleagueB 类实现了 Colleague 接口,它们通过中介者进行通信。
在 ColleagueA 和 ColleagueB 的构造函数中,中介者对象被传入,以便同事可以发送消息。
receiveMessage() 方法在同事类中定义,用于接收来自其他同事的消息。
sendMediatorMessage() 方法允许同事通过中介者发送消息给其他同事。
在 Client 类的 main 方法中,创建了中介者对象,并调用 createMediator() 方法来初始化同事。
然后,通过中介者,同事A和同事B互相发送消息。
*/

访问者模式(Visitor Pattern)

// 定义元素接口,它接受一个访问者对象
interface Element {
    void accept(Visitor visitor);
}

// 创建具体的元素类
class ConcreteElementA implements Element {
    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }

    // 其他与ConcreteElementA相关的操作
}

class ConcreteElementB implements Element {
    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }

    // 其他与ConcreteElementB相关的操作
}

// 定义访问者接口,它有一个访问元素的方法
interface Visitor {
    void visit(ConcreteElementA element);
    void visit(ConcreteElementB element);
}

// 创建具体的访问者类
class ConcreteVisitor implements Visitor {
    @Override
    public void visit(ConcreteElementA element) {
        // 对ConcreteElementA执行操作
        System.out.println("访问ConcreteElementA");
    }

    @Override
    public void visit(ConcreteElementB element) {
        // 对ConcreteElementB执行操作
        System.out.println("访问ConcreteElementB");
    }
}

// 客户端代码,使用访问者模式
public class Client {
    public static void main(String[] args) {
        // 创建元素对象
        Element elementA = new ConcreteElementA();
        Element elementB = new ConcreteElementB();

        // 创建访问者对象
        Visitor visitor = new ConcreteVisitor();

        // 元素接受访问者
        elementA.accept(visitor); // 输出: 访问ConcreteElementA
        elementB.accept(visitor); // 输出: 访问ConcreteElementB
    }
}

/*
代码解释:

Element 接口定义了一个 accept 方法,它接受一个 Visitor 对象作为参数。
ConcreteElementA 和 ConcreteElementB 类实现了 Element 接口,它们分别定义了如何接受访问者。
accept 方法在具体元素类中调用访问者的 visit 方法,传递当前元素对象作为参数。
Visitor 接口定义了两个 visit 方法,分别用于访问 ConcreteElementA 和 ConcreteElementB。
ConcreteVisitor 类实现了 Visitor 接口,定义了如何访问具体元素类。
在 ConcreteVisitor 类的 visit 方法中,可以定义对元素的具体操作。
在 Client 类的 main 方法中,创建了元素对象和访问者对象。
通过调用元素的 accept 方法,元素对象接受访问者对象,从而允许访问者对元素执行操作。
*/

备忘录模式(Memento Pattern)

// 创建一个备忘录类,用于存储原始对象的状态
class Memento {
    private final String state;

    public Memento(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }
}

// 创建一个发起人类,它将创建备忘录并可以恢复状态
class Originator {
    private String state;

    public void setState(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }

    // 创建一个备忘录,存储当前状态
    public Memento saveStateToMemento() {
        return new Memento(state);
    }

    // 恢复状态
    public void getStateFromMemento(Memento memento) {
        state = memento.getState();
    }
}

// 创建一个负责人类,它负责管理备忘录
class Caretaker {
    private Memento memento;

    public void setMemento(Memento memento) {
        this.memento = memento;
    }

    public Memento getMemento() {
        return memento;
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 创建原始对象
        Originator originator = new Originator();
        originator.setState("State #1");

        // 创建负责人对象
        Caretaker caretaker = new Caretaker();

        // 保存状态到备忘录
        caretaker.setMemento(originator.saveStateToMemento());

        // 改变原始对象的状态
        originator.setState("State #2");

        // 恢复原始对象的状态
        originator.getStateFromMemento(caretaker.getMemento());
        System.out.println("Restored State: " + originator.getState()); // 输出: Restored State: State #1
    }
}
/*
代码解释:

Memento 类是一个备忘录类,它存储了 Originator 对象的状态。getState 方法允许访问存储的状态。
Originator 类是原始对象,它有 setState 和 getState 方法来设置和获取状态。
saveStateToMemento 方法在 Originator 类中创建一个 Memento 对象,并将当前状态保存到备忘录中。
getStateFromMemento 方法允许 Originator 对象从 Memento 对象中恢复状态。
Caretaker 类是负责人类,它负责管理备忘录。它有一个 setMemento 方法来保存备忘录,以及一个 getMemento 方法来获取备忘录。
在 Client 类的 main 方法中,我们创建了一个 Originator 对象和一个 Caretaker 对象。
通过调用 saveStateToMemento 方法,我们保存了原始对象的初始状态到备忘录中。
然后,我们改变了原始对象的状态。
通过调用 getStateFromMemento 方法,我们从备忘录中恢复了原始对象的状态,并打印出恢复后的状态。
*/

解释器模式(Interpreter)

// 定义一个表达式接口
interface Expression {
    boolean interpret(String context);
}

// 创建一个终结符表达式类,它实现了表达式接口
class TerminalExpression implements Expression {
    @Override
    public boolean interpret(String context) {
        // 终结符表达式的解释逻辑,例如检查context中是否包含某个特定的关键字
        return context.contains("terminal");
    }
}

// 创建一个非终结符表达式类,它实现了表达式接口
class NonTerminalExpression implements Expression {
    private Expression expression;

    public NonTerminalExpression(Expression expression) {
        this.expression = expression;
    }

    @Override
    public boolean interpret(String context) {
        // 非终结符表达式的解释逻辑,例如调用子表达式的解释方法
        return expression.interpret(context);
    }
}

// 创建一个上下文环境,用于解释器模式
class Context {
    private String text;

    public Context(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 创建一个终结符表达式
        Expression terminal = new TerminalExpression();

        // 创建一个上下文环境
        Context context = new Context("This is a terminal expression");

        // 使用终结符表达式解释上下文
        boolean result = terminal.interpret(context.getText());
        System.out.println("Interpretation result: " + result); // 输出: Interpretation result: true

        // 如果需要,可以创建复杂的表达式树
        // 例如,一个非终结符表达式包含一个终结符表达式
        Expression nonTerminal = new NonTerminalExpression(terminal);
        result = nonTerminal.interpret(context.getText());
        System.out.println("Interpretation result: " + result); // 输出: Interpretation result: true
    }
}
/*
代码解释:

Expression 接口定义了一个 interpret 方法,该方法接受一个字符串上下文作为参数,并返回一个布尔值表示解释结果。
TerminalExpression 类实现了 Expression 接口,代表终结符表达式。终结符表达式是解释器模式中的最小单元,它直接对上下文进行解释。
interpret 方法在 TerminalExpression 类中实现了具体的解释逻辑,例如检查上下文中是否包含某个关键字。
NonTerminalExpression 类也实现了 Expression 接口,代表非终结符表达式。非终结符表达式可以包含其他表达式,形成一个表达式树。
NonTerminalExpression 类的构造函数接受一个 Expression 对象,它将作为子表达式。
interpret 方法在 NonTerminalExpression 类中调用子表达式的 interpret 方法,实现了更复杂的解释逻辑。
Context 类用于存储上下文信息,这里是一个简单的文本字符串。
在 Client 类的 main 方法中,我们创建了一个终结符表达式和一个上下文环境。
我们使用终结符表达式对上下文文本进行解释,并打印出解释结果。
我们也展示了如何创建一个非终结符表达式,它包含一个终结符表达式作为子节点,并对相同的上下文进行解释。
*/

命令模式(Command)

// 命令接口,定义执行操作的方法
interface Command {
    void execute();
}

// 接收者,知道如何实施与执行一个请求相关的操作
class Receiver {
    public void doSomething() {
        System.out.println("Receiver is doing something.");
    }
}

// 具体命令,将一个接收者对象与请求绑定
class ConcreteCommand implements Command {
    private Receiver receiver;

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

    @Override
    public void execute() {
        receiver.doSomething();
    }
}

// 调用者,要求该命令执行这个请求
class Invoker {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void executeCommand() {
        command.execute();
    }
}

// 客户端代码
public class CommandPatternClient {
    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Command command = new ConcreteCommand(receiver);
        Invoker invoker = new Invoker();

        invoker.setCommand(command);
        invoker.executeCommand(); // Receiver is doing something.
    }
}
/*
代码解释:
Command 接口定义了所有命令的统一接口 execute。
Receiver 类是实际执行命令的对象。
ConcreteCommand 类实现了 Command 接口,持有 Receiver 对象,并调用其 doSomething 方法。
Invoker 类持有一个 Command 对象,并执行该命令。
在 CommandPatternClient 类中,创建了 Receiver、Command 和 Invoker 的实例,并通过 Invoker 执行命令。
*/

状态模式(State)

// 状态接口,定义了状态的行为
interface State {
    void handle(StateContext context);
}

// 具体状态A,实现了状态接口
class ConcreteStateA implements State {
    @Override
    public void handle(StateContext context) {
        System.out.println("Handling in state A");
        context.setState(new ConcreteStateB());
    }
}

// 具体状态B,实现了状态接口
class ConcreteStateB implements State {
    @Override
    public void handle(StateContext context) {
        System.out.println("Handling in state B");
        // 可以切换回状态A或其他状态
    }
}

// 环境上下文,维持一个状态实例的引用
class StateContext {
    private State state;

    public void setState(State state) {
        this.state = state;
    }

    public State getState() {
        return state;
    }

    public void handleState() {
        state.handle(this);
    }
}

// 客户端代码
public class StatePatternClient {
    public static void main(String[] args) {
        StateContext context = new StateContext();
        context.setState(new ConcreteStateA());
  
        // 处理请求
        context.handleState(); // Handling in state A
        context.handleState(); // Handling in state B (假设ConcreteStateB中有状态切换逻辑)
    }
}
/*
代码解释
State 接口定义了所有状态的统一接口 handle。
ConcreteStateA 和 ConcreteStateB 类实现了 State 接口,分别定义了各自状态下的行为。
在 ConcreteStateA 的 handle 方法中,处理完状态A的逻辑后,将上下文的状态切换为 ConcreteStateB。
StateContext 类是环境上下文,它持有一个状态对象,并提供方法来改变状态和处理状态。
在 StatePatternClient 类中,创建了 StateContext 和状态对象的实例,并通过上下文处理状态。
*/

4、结构型模式

适配器模式(Adapter)

// 目标接口,定义客户端使用的特定领域相关的接口
interface Target {
    void request();
}

// 被适配者接口,有一个特定的方法需要适配
class Adaptee {
    public void specificRequest() {
        System.out.println("Executing specific request...");
    }
}

// 适配器类,将被适配者接口转换成目标接口
class Adapter implements Target {
    private Adaptee adaptee; // 引用被适配者对象

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    public void request() {
        adaptee.specificRequest(); // 调用被适配者的方法
    }
}

// 客户端使用适配器
public class AdapterPatternDemo {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request();
    }
}

装饰器模式(Decorator)

// 抽象构件,定义了对象的接口
interface Component {
    void operate();
}

// 具体构件,实现了抽象构件
class ConcreteComponent implements Component {
    public void operate() {
        System.out.println("ConcreteComponent operate");
    }
}

// 抽象装饰器,继承自构件类,可以装饰具体构件
abstract class Decorator implements Component {
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    public void operate() {
        component.operate();
    }
}

// 具体装饰器,继承自抽象装饰器,装饰具体构件
class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }

    public void operate() {
        super.operate(); // 调用被装饰对象的方法
        // 装饰器添加的行为
        System.out.println("Decorator added behavior");
    }
}

// 客户端使用装饰器
public class DecoratorPatternDemo {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        component = new ConcreteDecorator(component);
        component.operate();
    }
}

代理模式(Proxy)

// 真实主题,定义了代理对象所代表的真实对象
interface Subject {
    void request();
}

// 真实主题的实现
class RealSubject implements Subject {
    public void request() {
        System.out.println("RealSubject: Handling request.");
    }
}

// 代理主题,实现了与真实主题相同的接口
class Proxy implements Subject {
    private RealSubject realSubject;

    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        realSubject.request();
    }
}

// 客户端使用代理
public class ProxyPatternDemo {
    public static void main(String[] args) {
        Subject proxy = new Proxy();
        proxy.request();
    }
}

外观模式(Facade)

// 子系统中的各个组件
class SubSystemOne {
    public void operation1() {
        System.out.println("Operation of SubSystem One");
    }
}

class SubSystemTwo {
    public void operation2() {
        System.out.println("Operation of SubSystem Two");
    }
}

// 外观类,提供了一个客户端可以访问子系统功能的接口
class Facade {
    private SubSystemOne subOne;
    private SubSystemTwo subTwo;

    public Facade() {
        subOne = new SubSystemOne();
        subTwo = new SubSystemTwo();
    }

    public void operation() {
        subOne.operation1();
        subTwo.operation2();
    }
}

// 客户端使用外观模式
public class FacadePatternDemo {
    public static void main(String[] args) {
        Facade facade = new Facade();
        facade.operation();
    }
}

桥接模式(Bridge)

// 抽象部分
abstract class Abstraction {
    protected Implementation implementation;

    public Abstraction(Implementation implementation) {
        this.implementation = implementation;
    }

    public abstract void operation();
}

// 扩展抽象部分
class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(Implementation implementation) {
        super(implementation);
    }

    public void operation() {
        implementation.implementationOperation();
    }
}

// 实现部分
interface Implementation {
    void implementationOperation();
}

// 具体实现部分
class ConcreteImplementationA implements Implementation {
    public void implementationOperation() {
        System.out.println("ConcreteImplementationA operation");
    }
}

class ConcreteImplementationB implements Implementation {
    public void implementationOperation() {
        System.out.println("ConcreteImplementationB operation");
    }
}

// 客户端使用桥接模式
public class BridgePatternDemo {
    public static void main(String[] args) {
        Abstraction abstraction = new RefinedAbstraction(new ConcreteImplementationA());
        abstraction.operation();
    }
}

组合模式(Composite)

// 组件接口
interface Component {
    void operation();
}

// 树叶对象,实现了组件接口
class Leaf implements Component {
    public void operation() {
        System.out.println("Leaf operation");
    }
}

// 组合对象,也实现了组件接口
class Composite implements Component {
    private List<Component> children = new ArrayList<>();

    public void add(Component component) {
        children.add(component);
    }

    public void remove(Component component) {
        children.remove(component);
    }

    public void operation() {
        for (Component child : children) {
            child.operation();
        }
    }
}

// 客户端使用组合模式
public class CompositePatternDemo {
    public static void main(String[] args) {
        Composite root = new Composite();
        root.add(new Leaf());
        root.add(new Leaf());
        root.add(new Composite());
        ((Composite) root.children.get(2)).add(new Leaf());
        root.operation();
    }
}

享元模式(Flyweight)

// 享元对象
class Flyweight {
    private String intrinsicState;

    public Flyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    public void operation(String extrinsicState) {
        // 操作享元的内部状态和外部状态
        System.out.println("Flyweight operation with intrinsic: " + intrinsicState + " and extrinsic: " + extrinsicState);
    }
}

// 享元工厂,用于创建和管理享元对象
class FlyweightFactory {
    private static Map<String, Flyweight> flyweights = new HashMap<>();

    public static Flyweight getFlyweight(String intrinsicState) {
        if (!flyweights.containsKey(intrinsicState)) {
            flyweights.put(intrinsicState, new Flyweight(intrinsicState));
        }
        return flyweights.get(intrinsicState);
    }
}

// 客户端使用享元模式
public class FlyweightPatternDemo {
    public static void main(String[] args) {
        Flyweight flyweight1 = FlyweightFactory.getFlyweight("State1");
        flyweight1.operation("Extrinsic1");

        Flyweight flyweight2 = FlyweightFactory.getFlyweight("State2");
        flyweight2.operation("Extrinsic2");
    }
}
  • 57
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值