当前位置: 首页 > article >正文

软考 高级 架构师 第十一章 面向对象分析 设计模式

1.概述

架构模式:软件设计中的高层决策,例如C/S结构
设计模式:每个设计模式描述了一个在我们周围不断重复发生的问题,以及该问题的解决方案核心。有四个基本要素:模式名称、问题、解决方案、效果。
惯用法:最底层的模式,关注软件设计与实现,实现时通过某种特定的程序设计语言来描述构件之间的关系。

2.设计模式分类

设计模式可分为三类:
1)创建型,主要用作创建对象
2)结构型,,处理类和对象的组合
3)行为型,描述类和对象的交互行为
在这里插入图片描述

3.创建型

英文名中文定义记忆关键字
Abstract Factory抽象工厂提供一个接口,可以创建一系列相关或相互依赖的对象,而无须指定它们具体的类抽象接口
Factory Method工厂定义创建一个对象的接口,但由子类决定需要实例化哪个类子类决定实例化
Builder构造器将一个复杂类的表示与其构造相分离,使得相得构造过程能够得到不同的表示类和构造分离
Prototype原型用原型实例指定创建对象的类型,通过拷贝来创建对象原型实例,拷贝
Singleton单例保证一个类只有一个实例,并提供一个访问它的全局访问点唯一实例

3.1.抽象工厂模式

抽象工厂模式的每个具体工厂实现类负责创建一系列相关的产品对象。
例:


```java

```java

```java

```java
// 抽象产品类:动物
interface Animal {
    void makeSound();
}
 
// 具体产品类:狗
class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}
 
// 具体产品类:猫
class Cat implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}
 
// 抽象产品类:动物配件
interface AnimalAccessory {
    void useAccessory();
}
 
// 具体产品类:狗项圈
class DogCollar implements AnimalAccessory {
    @Override
    public void useAccessory() {
        System.out.println("Using Dog Collar");
    }
}
 
// 具体产品类:猫项圈
class CatCollar implements AnimalAccessory {
    @Override
    public void useAccessory() {
        System.out.println("Using Cat Collar");
    }
}
 
// 抽象工厂类:定义创建动物及其配件的接口
interface AnimalFactory {
    Animal createAnimal();
    AnimalAccessory createAccessory();
}
 
// 具体工厂类:生产狗及其配件
class DogFactory implements AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Dog();
    }
 
    @Override
    public AnimalAccessory createAccessory() {
        return new DogCollar();
    }
}
 
// 具体工厂类:生产猫及其配件
class CatFactory implements AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Cat();
    }
 
    @Override
    public AnimalAccessory createAccessory() {
        return new CatCollar();
    }
}

3.2.工厂模式

public interface Animal {
    void makeSound();
}

public class Cat implements Animal {
    @Override
    public void makeSound() {
        System.out.println("喵~");
    }
}
 
public class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("汪~");
    }
 
public class Tiger implements Animal {
    @Override
    public void makeSound() {
        System.out.println("吼~");
    }
}

简单工厂:
public class AnimalFactory {
    public static Animal createAnimal(String type) {
        if ("cat".equals(type)) {
            return new Cat();
        } else if ("dog".equals(type)) {
            return new Dog();
        } else if ("tiger".equals(type)) {
            return new Tiger();
        }
        return null;
    }
}

工厂方法(工厂方法模式的每个具体工厂实现类只负责创建一种具体产品。):
public interface AnimalFactory {
    Animal createAnimal();
}
 
public class CatFactory implements AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Cat();
    }
}
 
public class DogFactory implements AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Dog();
    }
}
 
public class TigerFactory implements AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Tiger();
    }
}

3.3.原型模式

例:

// 抽象原型接口
interface Prototype {
    Prototype clone();
}
 
// 具体原型类
class ConcretePrototype implements Prototype {
    private String field;
 
    public ConcretePrototype(String field) {
        this.field = field;
    }
 
    @Override
    public Prototype clone() {
        // 简单地通过new关键字创建一个新的实例,并复制字段值
        return new ConcretePrototype(this.field);
    }
 
    public void setField(String field) {
        this.field = field;
    }
 
    public String getField() {
        return field;
    }
}

3.4.单例模式

//饿汉模式:
public class EagerSingleton {
    private static final EagerSingleton instance = new EagerSingleton();
 
    private EagerSingleton() {
    }
 
    public static EagerSingleton getInstance() {
        return instance;
    }
}

//懒汉模式:
public class Singleton {
    private static volatile Singleton instance = null;
 
    private Singleton() {
    }
 
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

3.5.构造器模式

例:

public class Person {
    private String firstName;
    private String lastName;
    private int age;
    private String address;
 
    // 私有构造器,防止外部直接创建 Person 实例
    private Person(String firstName, String lastName, int age, String address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.address = address;
    }
 
    // 公共静态内部类,用于构建 Person 对象
    public static class Builder {
        private String firstName;
        private String lastName;
        private int age;
        private String address;
 
        // 设置 firstName
        public Builder setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }
 
        // 设置 lastName
        public Builder setLastName(String lastName) {
            this.lastName = lastName;
            return this;
        }
 
        // 设置 age
        public Builder setAge(int age) {
            this.age = age;
            return this;
        }
 
        // 设置 address
        public Builder setAddress(String address) {
            this.address = address;
            return this;
        }
 
        // 构建并返回 Person 对象
        public Person build() {
            return new Person(firstName, lastName, age, address);
        }
    }
}

4.结构型

英文名中文定义记忆关键字
Adaptor适配器将一个类的接口转换成用户期望得到的另一种接口。它使原本不能相容的接口得以协同工作。转换,兼容接口
Bridge桥接模式将类的抽象部分和它的实现部分分离开来,使它们可以独立的变化。抽象和实现分离
Composite组合模式将对象组合成树形结构以表示整体-部分的层次结构,使得用户对单个对象和组合对象的使用具有一致性整体-部分,树形结构
Decorator装饰模式动态地给一个对象添加一些额外的职责。他提供了用子类拓展功能的一个灵活的替代,比派生一个子类更加灵活。如java的流。附加职责
Facade外观模式定义一个高层接口,为子系统中的一组接口提供一个一致的外观,从而简化了该子系统额使用。对外统一接口
Flyweight享元模式提供支持大量细粒度对象共享的使用细粒度、共享
Proxy代理模式为恰对象 提供一种代理以控制这个对象的访问代理控制

4.1.适配器模式

例:

// 目标接口
interface Target {
    void request();
}
 
// 需要适配的类
class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request.");
    }
}
 
// 适配器类
class Adapter implements Target {
    private Adaptee adaptee;
 
    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
 
    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

4.2.桥接模式
例:

// 实现接口
interface DrawAPI {
    public void drawCircle(int radius, int x, int y);
}
 
// 具体实现类
class RedCircle implements DrawAPI {
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", y: " + y + "]");
    }
}
 
// 抽象类
abstract class Shape {
    protected DrawAPI drawAPI;
 
    protected Shape(DrawAPI drawAPI) {
        this.drawAPI = drawAPI;
    }
 
    public abstract void draw();
}
 
// 具体形状类
class Circle extends Shape {
    private int x, y, radius;
 
    public Circle(int x, int y, int radius, DrawAPI drawAPI) {
        super(drawAPI);
        this.x = x;
        this.y = y;
        this.radius = radius;
    }
 
    public void draw() {
        drawAPI.drawCircle(radius, x, y);
    }
}

4.3.组合模式

例:

// 组件接口
interface Component {
    void show();
}
 
// 叶子类
class Leaf implements Component {
    private String name;
 
    public Leaf(String name) {
        this.name = name;
    }
 
    public void show() {
        System.out.println("Leaf: " + name);
    }
}
 
// 组合类
class Composite implements Component {
    private List<Component> children = new ArrayList<>();
 
    public void add(Component component) {
        children.add(component);
    }
 
    public void show() {
        for (Component component : children) {
            component.show();
        }
    }
}

4.4.装饰模式

例:

// 接口
interface Shape {
    void draw();
}
 
// 具体实现类
class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing Circle");
    }
}
 
// 抽象装饰器
abstract class ShapeDecorator implements Shape {
    protected Shape decoratedShape;
 
    public ShapeDecorator(Shape decoratedShape) {
        this.decoratedShape = decoratedShape;
    }
 
    public void draw() {
        decoratedShape.draw();
    }
}
 
// 具体装饰器
class RedShapeDecorator extends ShapeDecorator {
    public RedShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }
 
    @Override
    public void draw() {
        decoratedShape.draw();
        setRedBorder();
    }
 
    private void setRedBorder() {
        System.out.println("Setting Red Border");
    }
}

4.5.外观模式

例:

// 子系统类A
class SubSystemA {
    public void operationA() {
        System.out.println("Operation A");
    }
}
 
// 子系统类B
class SubSystemB {
    public void operationB() {
        System.out.println("Operation B");
    }
}
 
// 外观类
class Facade {
    private SubSystemA subSystemA;
    private SubSystemB subSystemB;
 
    public Facade() {
        subSystemA = new SubSystemA();
        subSystemB = new SubSystemB();
    }
 
    public void operation() {
        subSystemA.operationA();
        subSystemB.operationB();
    }
}

4.6.享元模式

例:

// 抽象享元类
interface Flyweight {
    void operation(String extrinsicState);
}
 
// 具体享元类
class ConcreteFlyweight implements Flyweight {
    private final String intrinsicState;
 
    public ConcreteFlyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }
 
    public void operation(String extrinsicState) {
        System.out.println("Intrinsic State = " + intrinsicState + ", Extrinsic State = " + extrinsicState);
    }
}
 
// 享元工厂类
class FlyweightFactory {
    private final Map<String, Flyweight> flyweights = new HashMap<>();
 
    public Flyweight getFlyweight(String key) {
        Flyweight flyweight = flyweights.get(key);
        if (flyweight == null) {
            flyweight = new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
 
    public int getFlyweightCount() {
        return flyweights.size();
    }
}

4.7.代理模式

例:

// 抽象主题接口
interface Subject {
    void request();
}
 
// 真实主题类,实现了 Subject 接口
class RealSubject implements Subject {
    @Override
    public void request() {
        System.out.println("RealSubject: Handling request.");
    }
}
 
// 代理类,也实现了 Subject 接口
class Proxy implements Subject {
    private RealSubject realSubject;
 
    @Override
    public void request() {
        // 在访问真实主题之前,可以执行一些附加操作
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        System.out.println("Proxy: Logging the time of request.");
        realSubject.request();
        // 在访问真实主题之后,也可以执行一些附加操作
        System.out.println("Proxy: Request has been handled.");
    }
}

5.行为型

英文名中文定义记忆关键字
Chain of Responsibility职责链模式通过给多个对象处理请求的机会,减少请求的发送者与接受者之间的耦合。将接收对象链接起来,在链中传递请求,知道有一个对象处理这个请求。传递请求、职责、链接
Command命令模式 将一个请求封装为一个对象,从而可用不同 的请求都客户进行参数化,将请求排队或记录请求日志,支持可撤销的操作。日志记录、可撤销
Interpreter解释器模式给定一种语言,定义他的问法表示,并定义一个解释器,该解释器用来根据文法来解释语言中的句子解释器,虚拟机
Iterator迭代器模式提供一种方法来顺序访问一个聚合对象中的各个元素而不需要暴露该对象的内部表示顺序访问,不暴露内部
Mediator中介者模式用一个中介对象来封装一系列的对象交互。它使各对象不需要显示地相互调用,从而达到低耦合,还可以独立地改变对象见间的交互不直接引用
Memento备忘录模式在不破坏封装性的前提前下,捕获一个对象的内部状态,并在该对象之外保存这个状态,从而可以在以后将该对象恢复到原先保存的状态保存、恢复
Observer观察者模式 定义对象的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新通知、自动更新
State状态模式允许一个对象在其内部状态改变时改变它的行为状态变成类
Strategy策略模式定义一些列算法,把他们一个个封装起来,并且使它们之间可相互替换,从而让算法可以独立于使用它的用户而变化。算法替换
Template Method模板方法模式定义一个操作中的算法骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义算法的某些特定步骤定义算法骨架,然后在细化
Visitor访问者模式表示一个作用于某对象结构中的各元素的操作,使得在不改变各元素的类的前提下定义作用于这些元素的新操作数据和操作分离

5.1.职责链模式

例:

// 抽象处理者
abstract class Handler {
    Handler handler;
 
    public void setHandler(Handler handler) {
        this.handler = handler;
    }
 
    abstract void handleRequest(int requestNum);
}
 
// 具体处理者A
class ConcreteHandlerA extends Handler {
    @Override
    public void handleRequest(int requestNum) {
        if (requestNum > 10) {
            System.out.println("ConcreteHandlerA 处理");
        } else {
            if (handler != null) {
                handler.handleRequest(requestNum);
            }
        }
    }
}
 
// 具体处理者B
class ConcreteHandlerB extends Handler {
    @Override
    public void handleRequest(int requestNum) {
        if (requestNum < 10) {
            System.out.println("ConcreteHandlerB 处理");
        } else {
            if (handler != null) {
                handler.handleRequest(requestNum);
            }
        }
    }
}
 
// 客户端代码
public class Client {
    public static void main(String[] args) {
        Handler handlerA = new ConcreteHandlerA();
        Handler handlerB = new ConcreteHandlerB();
        handlerA.setHandler(handlerB);
        handlerA.handleRequest(11);
    }
}

5.2.命令模式

例:

// 命令接口
interface Command {
    void execute();
    void undo();
}
 
// 具体命令实现
class LightOnCommand implements Command {
    private Light light;
 
    public LightOnCommand(Light light) {
        this.light = light;
    }
 
    @Override
    public void execute() {
        light.on();
    }
 
    @Override
    public void undo() {
        light.off();
    }
}
 
// 接收者类
class Light {
    public void on() {
        System.out.println("The light is on");
    }
 
    public void off() {
        System.out.println("The light is off");
    }
}
 
// 调用者类
class Invoker {
    private Command command;
 
    public void setCommand(Command command) {
        this.command = command;
    }
 
    public void executeCommand() {
        command.execute();
    }
 
    public void undoCommand() {
        command.undo();
    }
}
 
// 客户端代码
public class CommandPatternDemo {
    public static void main(String[] args) {
        Light light = new Light();
        Command lightOnCommand = new LightOnCommand(light);
 
        Invoker invoker = new Invoker();
        invoker.setCommand(lightOnCommand);
 
        invoker.executeCommand(); // 执行命令
        invoker.undoCommand();    // 撤销命令
    }
}

5.3.解释器模式

例:

// 抽象表达式
interface Expression {
    int interpret();
}
 
// 终结符表达式:数字
class TerminalExpression implements Expression {
    private int value;
 
    public TerminalExpression(int value) {
        this.value = value;
    }
 
    @Override
    public int interpret() {
        return value;
    }
}
 
// 非终结符表达式:加法
class AddExpression implements Expression {
    private Expression expr1;
    private Expression expr2;
 
    public AddExpression(Expression expr1, Expression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }
 
    @Override
    public int interpret() {
        return expr1.interpret() + expr2.interpret();
    }
}
 
// 非终结符表达式:乘法
class MulExpression implements Expression {
    private Expression expr1;
    private Expression expr2;
 
    public MulExpression(Expression expr1, Expression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }
 
    @Override
    public int interpret() {
        return expr1.interpret() * expr2.interpret();
    }
}
// 客户端代码
public class Client {
    public static void main(String[] args) {
        Expression expr1 = new TerminalExpression(10);
        Expression expr2 = new TerminalExpression(5);
 
        Expression addExpr = new AddExpression(expr1, expr2);
        System.out.println("加法结果: " + addExpr.interpret());
 
        Expression mulExpr = new MulExpression(expr1, expr2);
        System.out.println("乘法结果: " + mulExpr.interpret());
    }
}

5.4.迭代器模式

例:

// 抽象迭代器
interface Iterator {
    boolean hasNext();
    Object next();
}
 
// 具体迭代器
class ConcreteIterator implements Iterator {
    private List<Object> list;
    private int index;
 
    public ConcreteIterator(List<Object> list) {
        this.list = list;
        this.index = 0;
    }
 
    @Override
    public boolean hasNext() {
        return index < list.size();
    }
 
    @Override
    public Object next() {
        if (hasNext()) {
            return list.get(index++);
        } else {
            throw new NoSuchElementException();
        }
    }
}
 
// 聚合对象
class Aggregate {
    private List<Object> list;
 
    public Aggregate() {
        list = new ArrayList<>();
    }
 
    public void add(Object obj) {
        list.add(obj);
    }
 
    public void remove(Object obj) {
        list.remove(obj);
    }
 
    public Iterator createIterator() {
        return new ConcreteIterator(list);
    }
}
 
// 客户端代码
public class Client {
    public static void main(String[] args) {
        Aggregate aggregate = new Aggregate();
        aggregate.add("A");
        aggregate.add("B");
        aggregate.add("C");
 
        Iterator iterator = aggregate.createIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

5.5.中介者模式

例:

// 抽象中介者接口
interface Mediator {
    void sendMessage(String message, User user);
}
 
// 同事类:用户
class User {
    private String name;
    private Mediator mediator;
 
    public User(String name, Mediator mediator) {
        this.name = name;
        this.mediator = mediator;
    }
 
    public void send(String message) {
        System.out.println(name + " sends: " + message);
        mediator.sendMessage(message, this);
    }
 
    public void receive(String message) {
        System.out.println(name + " receives: " + message);
    }
 
    public String getName() {
        return name;
    }
}
 
// 具体中介者实现
class ChatRoom implements Mediator {
    private List<User> users = new ArrayList<>();
 
    public void addUser(User user) {
        users.add(user);
    }
 
    @Override
    public void sendMessage(String message, User sender) {
        for (User user : users) {
            if (!user.getName().equals(sender.getName())) {
                user.receive(message);
            }
        }
    }
}
 
// 客户端代码
public class MediatorPatternDemo {
    public static void main(String[] args) {
        Mediator mediator = new ChatRoom();
 
        User user1 = new User("Alice", mediator);
        User user2 = new User("Bob", mediator);
        User user3 = new User("Charlie", mediator);
 
        ChatRoom chatRoom = (ChatRoom) mediator;
        chatRoom.addUser(user1);
        chatRoom.addUser(user2);
        chatRoom.addUser(user3);
 
        user1.send("Hello everyone!");
        user2.send("Hi Alice!");
        user3.send("Hey guys, what's up?");
    }
}

5.6.备忘录模式

例:

// 发起人(Originator)
class Article {
    private String content;
 
    public Article(String content) {
        this.content = content;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
 
    // 创建备忘录
    public ArticleMemento createMemento() {
        return new ArticleMemento(content);
    }
 
    // 恢复备忘录
    public void restoreMemento(ArticleMemento memento) {
        this.content = memento.getContent();
    }
}
 
// 备忘录(Memento)
class ArticleMemento {
    private String content;
 
    public ArticleMemento(String content) {
        this.content = content;
    }
 
    public String getContent() {
        return content;
    }
}
 
// 管理者(Caretaker)
class ArticleCaretaker {
    private List<ArticleMemento> mementos = new ArrayList<>();
 
    public void addMemento(ArticleMemento memento) {
        mementos.add(memento);
    }
 
    public ArticleMemento getMemento(int index) {
        return mementos.get(index);
    }
}
 
// 客户端代码
public class MementoPatternDemo {
    public static void main(String[] args) {
        Article article = new Article("First draft");
 
        ArticleCaretaker caretaker = new ArticleCaretaker();
 
        // 保存当前状态
        caretaker.addMemento(article.createMemento());
 
        // 修改文章内容
        article.setContent("Second draft");
 
        // 恢复之前的状态
        article.restoreMemento(caretaker.getMemento(0));
 
        System.out.println("Article content: " + article.getContent());
    }
}

5.7.观察者模式

例:

// 观察者接口
interface Observer {
    void update(String message);
}
 
// 具体观察者实现
class ConcreteObserver implements Observer {
    private String name;
 
    public ConcreteObserver(String name) {
        this.name = name;
    }
 
    @Override
    public void update(String message) {
        System.out.println(name + " received message: " + message);
    }
}
 
// 主体(Subject)
class Subject {
    private List<Observer> observers = new ArrayList<>();
 
    public void attach(Observer observer) {
        observers.add(observer);
    }
 
    public void detach(Observer observer) {
        observers.remove(observer);
    }
 
    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}
 
// 客户端代码
public class ObserverPatternDemo {
    public static void main(String[] args) {
        Subject subject = new Subject();
 
        Observer observer1 = new ConcreteObserver("Alice");
        Observer observer2 = new ConcreteObserver("Bob");
 
        subject.attach(observer1);
        subject.attach(observer2);
 
        subject.notifyObservers("Hello Observers!");
 
        subject.detach(observer1);
        subject.notifyObservers("Hello Remaining Observers!");
    }
}

5.8.状态模式

例:

// 抽象状态接口
interface State {
    void handle(Player player);
}
 
// 具体状态类:正常状态
class NormalState implements State {
    @Override
    public void handle(Player player) {
        System.out.println("Player is in normal state.");
    }
}
 
// 具体状态类:受伤状态
class InjuredState implements State {
    @Override
    public void handle(Player player) {
        System.out.println("Player is injured.");
    }
}
 
// 具体状态类:危急状态
class CriticalState implements State {
    @Override
    public void handle(Player player) {
        System.out.println("Player is in critical condition.");
    }
}
 
// 环境类
class Player {
    private State currentState;
    private int health;
 
    public Player() {
        this.currentState = new NormalState(); // 初始状态为正常状态
        this.health = 100;
    }
 
    public void setHealth(int health) {
        this.health = health;
        changeState();
    }
 
    private void changeState() {
        if (health > 70) {
            currentState = new NormalState();
        } else if (health > 30) {
            currentState = new InjuredState();
        } else {
            currentState = new CriticalState();
        }
    }
 
    public void reportState() {
        currentState.handle(this);
    }
}
 
// 客户端代码
public class StatePatternDemo {
    public static void main(String[] args) {
        Player player = new Player();
        player.reportState(); // 输出: Player is in normal state.
 
        player.setHealth(50);
        player.reportState(); // 输出: Player is injured.
 
        player.setHealth(20);
        player.reportState(); // 输出: Player is in critical condition.
    }
}

5.9.策略模式

例:

// 策略接口
interface Strategy {
    int doOperation(int num1, int num2);
}
 
// 具体策略类:加法
class OperationAdd implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}
 
// 具体策略类:减法
class OperationSubtract implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}
 
// 环境类
class Context {
    private Strategy strategy;
 
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }
 
    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}
 
// 客户端代码
public class StrategyPatternDemo {
    public static void main(String[] args) {
        Context context = new Context(new OperationAdd());
        System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
 
        context = new Context(new OperationSubtract());
        System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
    }
}

5.10.模板方法模式

例:

// 抽象类,定义模板方法
abstract class Game {
    abstract void initialize();
    abstract void startPlay();
    abstract void endPlay();
 
    // 模板方法
    public final void play() {
        initialize();
        startPlay();
        endPlay();
    }
}
 
// 具体类:足球
class Football extends Game {
    @Override
    void initialize() {
        System.out.println("Football Game Initialized! Start playing.");
    }
 
    @Override
    void startPlay() {
        System.out.println("Football Game Started. Enjoy the game!");
    }
 
    @Override
    void endPlay() {
        System.out.println("Football Game Finished!");
    }
}
 
// 具体类:板球
class Cricket extends Game {
    @Override
    void initialize() {
        System.out.println("Cricket Game Initialized! Start playing.");
    }
 
    @Override
    void startPlay() {
        System.out.println("Cricket Game Started. Enjoy the game!");
    }
 
    @Override
    void endPlay() {
        System.out.println("Cricket Game Finished!");
    }
}
 
// 客户端代码
public class TemplateMethodPatternDemo {
    public static void main(String[] args) {
        Game game = new Football();
        game.play();
        System.out.println();
        game = new Cricket();
        game.play();
    }
}

5.11.访问者模式

例:

// 元素接口
interface ComputerPart {
    void accept(ComputerPartVisitor visitor);
}
 
// 具体元素类:键盘
class Keyboard implements ComputerPart {
    @Override
    public void accept(ComputerPartVisitor visitor) {
        visitor.visit(this);
    }
}
 
// 具体元素类:鼠标
class Mouse implements ComputerPart {
    @Override
    public void accept(ComputerPartVisitor visitor) {
        visitor.visit(this);
    }
}
 
// 具体元素类:显示器
class Monitor implements ComputerPart {
    @Override
    public void accept(ComputerPartVisitor visitor) {
        visitor.visit(this);
    }
}
 
// 访问者接口
interface ComputerPartVisitor {
    void visit(ComputerPart part);
    void visit(Keyboard keyboard);
    void visit(Mouse mouse);
    void visit(Monitor monitor);
}
 
// 具体访问者类:计算机维修
class ComputerPartDisplayVisitor implements ComputerPartVisitor {
    @Override
    public void visit(ComputerPart part) {
        // 通用行为(可选)
    }
 
    @Override
    public void visit(Keyboard keyboard) {
        System.out.println("Displaying Keyboard.");
    }
 
    @Override
    public void visit(Mouse mouse) {
        System.out.println("Displaying Mouse.");
    }
 
    @Override
    public void visit(Monitor monitor) {
        System.out.println("Displaying Monitor.");
    }
}
 
// 客户端代码
public class VisitorPatternDemo {
    public static void main(String[] args) {
        ComputerPart keyboard = new Keyboard();
        ComputerPart mouse = new Mouse();
        ComputerPart monitor = new Monitor();
 
        ComputerPart[] parts = {keyboard, mouse, monitor};
 
        ComputerPartDisplayVisitor visitor = new ComputerPartDisplayVisitor();
 
        for (ComputerPart part : parts) {
            part.accept(visitor);
        }
    }
}

http://www.kler.cn/a/488637.html

相关文章:

  • 2024年度漏洞态势分析报告,需要访问自取即可!(PDF版本)
  • List详解 - 双向链表的操作
  • 代码随想录算法训练营第六十天|KM94.城市间货物运输Ⅰ|KM95.城市间货物运输Ⅱ|KM96.城市间货物运输Ⅲ
  • Ruby语言的软件开发工具
  • 【测试】——Cucumber入门
  • MATLAB深度学习实战文字识别
  • 天童美语:如何培养孩子的音乐细胞
  • 测试开发之面试宝典
  • mysql中查询json的技巧
  • 【大模型入门指南 07】量化技术浅析
  • Redis高频知识点
  • 【硬件测试】基于FPGA的BPSK+帧同步系统开发与硬件片内测试,包含高斯信道,误码统计,可设置SNR
  • GaussDB事务和并发控制机制
  • Unity Burst详解
  • Zustand selector 发生 infinate loops的原因以及解决
  • Unity Android AAB包GooglePlay上线备忘
  • vmware-ubuntu22.04配置虚拟机win10,重新上网成功
  • pyTorch笔记
  • 【网络】计算机网络的分类 局域网 (LAN) 广域网 (WAN) 城域网 (MAN)个域网(PAN)
  • 英伟达多维进击汽车业务:自动驾驶时代已至
  • 02-51单片机数码管与矩阵键盘
  • 分布式Id方案选择
  • NLP三大特征抽取器:CNN、RNN与Transformer全面解析
  • vue video重复视频 设置 srcObject 视频流不占用资源 减少资源浪费
  • 跟着逻辑先生学习FPGA-第六课 无源蜂鸣器发声实验
  • 解释器模式详解