设计模式的原理及深入解析

news/2025/6/20 12:24:12

创建型模式

创建型模式主要关注对象的创建过程,旨在通过不同的方式创建对象,以满足不同的需求。

工厂方法模式

定义:定义一个创建对象的接口,让子类决定实例化哪一个类。

解释:工厂方法模式通过定义一个创建对象的接口,允许子类决定实例化哪一个类。这样,客户端代码可以针对接口编程,而不必依赖于具体类。

代码示例

// 产品接口
interface Product {void use();
}// 具体产品A
class ConcreteProductA implements Product {public void use() {System.out.println("Using ConcreteProductA");}
}// 具体产品B
class ConcreteProductB implements Product {public void use() {System.out.println("Using ConcreteProductB");}
}// 抽象工厂
abstract class Creator {public abstract Product factoryMethod();public void someOperation() {Product product = factoryMethod();product.use();}
}// 具体工厂A
class ConcreteCreatorA extends Creator {public Product factoryMethod() {return new ConcreteProductA();}
}// 具体工厂B
class ConcreteCreatorB extends Creator {public Product factoryMethod() {return new ConcreteProductB();}
}

抽象工厂模式

定义:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

解释:抽象工厂模式通过定义一个创建对象的接口,允许子类决定实例化哪一个类。这样,客户端代码可以针对接口编程,而不必依赖于具体类。

代码示例

// 产品A接口
interface ProductA {void use();
}// 产品B接口
interface ProductB {void use();
}// 具体产品A1
class ConcreteProductA1 implements ProductA {public void use() {System.out.println("Using ConcreteProductA1");}
}// 具体产品B1
class ConcreteProductB1 implements ProductB {public void use() {System.out.println("Using ConcreteProductB1");}
}// 具体产品A2
class ConcreteProductA2 implements ProductA {public void use() {System.out.println("Using ConcreteProductA2");}
}// 具体产品B2
class ConcreteProductB2 implements ProductB {public void use() {System.out.println("Using ConcreteProductB2");}
}// 抽象工厂
interface AbstractFactory {ProductA createProductA();ProductB createProductB();
}// 具体工厂1
class ConcreteFactory1 implements AbstractFactory {public ProductA createProductA() {return new ConcreteProductA1();}public ProductB createProductB() {return new ConcreteProductB1();}
}// 具体工厂2
class ConcreteFactory2 implements AbstractFactory {public ProductA createProductA() {return new ConcreteProductA2();}public ProductB createProductB() {return new ConcreteProductB2();}
}

建造者模式

定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

解释:建造者模式通过将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。这样,客户端代码可以针对接口编程,而不必依赖于具体类。

代码示例

// 产品类
class Product {private String partA;private String partB;private String partC;public void setPartA(String partA) {this.partA = partA;}public void setPartB(String partB) {this.partB = partB;}public void setPartC(String partC) {this.partC = partC;}public void show() {System.out.println("Product Parts: " + partA + " " + partB + " " + partC);}
}// 抽象建造者
interface Builder {void buildPartA();void buildPartB();void buildPartC();Product getProduct();
}// 具体建造者
class ConcreteBuilder implements Builder {private Product product = new Product();public void buildPartA() {product.setPartA("PartA");}public void buildPartB() {product.setPartB("PartB");}public void buildPartC() {product.setPartC("PartC");}public Product getProduct() {return product;}
}// 指挥者
class Director {private Builder builder;public Director(Builder builder) {this.builder = builder;}public void construct() {builder.buildPartA();builder.buildPartB();builder.buildPartC();}
}

原型模式

定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

解释:原型模式通过复制现有实例来创建新实例,而不是通过新建实例。这样,可以避免复杂的构造过程。

代码示例

// 原型类
class Prototype implements Cloneable {private String prototypeName;public Prototype(String prototypeName) {this.prototypeName = prototypeName;}public String getPrototypeName() {return prototypeName;}public void setPrototypeName(String prototypeName) {this.prototypeName = prototypeName;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}// 客户端代码
public class Client {public static void main(String[] args) throws CloneNotSupportedException {Prototype p1 = new Prototype("Prototype1");Prototype p2 = (Prototype) p1.clone();p2.setPrototypeName("Prototype2");System.out.println(p1.getPrototypeName());System.out.println(p2.getPrototypeName());}
}
单例模式

定义:确保一个类只有一个实例,并提供一个全局访问点。

解释:单例模式通过确保一个类只有一个实例,并提供一个全局访问点,来控制对象的创建和访问。这样,可以避免创建多个实例,节省资源。

// 单例类
class Singleton {private static Singleton instance;private Singleton() {}public static Singleton getInstance() {if (instance == null) {instance = new Singleton();}return instance;}
}// 客户端代码
public class Client {public static void main(String[] args) {Singleton s1 = Singleton.getInstance();Singleton s2 = Singleton.getInstance();System.out.println(s1 == s2); // 输出:true}
}

结构型模式

结构型模式主要关注对象之间的组合,通过组合对象来实现新的功能,而不改变对象的结构。

适配器模式

定义:将一个类的接口转换成客户希望的另一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

解释:适配器模式通过将一个类的接口转换成客户希望的另一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

// 目标接口
interface Target {void request();
}// 需要适配的类
class Adaptee {public void specificRequest() {System.out.println("Specific request");}
}// 适配器
class Adapter extends Adaptee implements Target {public void request() {specificRequest();}
}// 客户端代码
public class Client {public static void main(String[] args) {Target target = new Adapter();target.request();}
}

装饰器模式

定义:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。

解释:装饰器模式通过动态地给一个对象添加一些额外的职责,使得增加功能更加灵活。

// 抽象构件
interface Component {void operation();
}// 具体构件
class ConcreteComponent implements Component {public void operation() {System.out.println("ConcreteComponent");}
}// 装饰抽象类
abstract class Decorator implements Component {protected Component component;public Decorator(Component component) {this.component = component;}public void operation() {component.operation();}
}// 具体装饰类A
class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component component) {super(component);}public void operation() {super.operation();addBehavior();}public void addBehavior() {System.out.println("ConcreteDecoratorA");}
}// 具体装饰类B
class ConcreteDecoratorB extends Decorator {public ConcreteDecoratorB(Component component) {super(component);}public void operation() {super.operation();addBehavior();}public void addBehavior() {System.out.println("ConcreteDecoratorB");}
}// 客户端代码
public class Client {public static void main(String[] args) {Component component = new ConcreteComponent();component = new ConcreteDecoratorA(component);component = new ConcreteDecoratorB(component);component.operation();}
}

桥接模式

定义:将抽象部分与实现部分分离,使它们都可以独立地变化。

解释:桥接模式通过将抽象部分与实现部分分离,使它们都可以独立地变化。

// 抽象类
abstract class Abstraction {protected Implementor implementor;public Abstraction(Implementor implementor) {this.implementor = implementor;}abstract public void operation();
}// 实现接口
interface Implementor {void implement();
}// 具体实现A
class ConcreteImplementorA implements Implementor {public void implement() {System.out.println("ConcreteImplementorA");}
}// 具体实现B
class ConcreteImplementorB implements Implementor {public void implement() {System.out.println("ConcreteImplementorB");}
}// 具体抽象类RefinedAbstraction
class RefinedAbstraction extends Abstraction {public RefinedAbstraction(Implementor implementor) {super(implementor);}public void operation() {implementor.implement();}
}// 客户端代码
public class Client {public static void main(String[] args) {Implementor implementor = new ConcreteImplementorA();Abstraction abstraction = new RefinedAbstraction(implementor);abstraction.operation();}
}

组合模式

定义:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得客户对单个对象和组合对象的使用具有一致性。

解释:组合模式通过将对象组合成树形结构以表示“部分-整体”的层次结构,使得客户对单个对象和组合对象的使用具有一致性。

// 抽象构件
abstract class Component {protected String name;public Component(String name) {this.name = name;}abstract public void add(Component component);abstract public void remove(Component component);abstract public void display(int depth);
}// 叶子构件
class Leaf extends Component {public Leaf(String name) {super(name);}public void add(Component component) {}public void remove(Component component) {}public void display(int depth) {System.out.println("-".repeat(depth) + name);}
}// 树枝构件
class Composite extends Component {private List<Component> childList = new ArrayList<>();public Composite(String name) {super(name);}public void add(Component component) {childList.add(component);}public void remove(Component component) {childList.remove(component);}public void display(int depth) {System.out.println("-".repeat(depth) + name);for (Component component : childList) {component.display(depth + 2);}}
}// 客户端代码
public class Client {public static void main(String[] args) {Component root = new Composite("root");Component branch1 = new Composite("branch1");Component branch2 = new Composite("branch2");Component leaf1 = new Leaf("leaf1");Component leaf2 = new Leaf("leaf2");root.add(branch1);root.add(branch2);branch1.add(leaf1);branch2.add(leaf2);root.display(1);}
}

外观模式

定义:为子系统中的一组接口提供一个一致的界面。外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

解释:外观模式通过为子系统中的一组接口提供一个一致的界面,使得这一子系统更加容易使用。
实现特点

  • 封装子系统复杂交互逻辑
  • 对外提供简化访问入口
  • 降低客户端与子系统的耦合度
// 子系统组件A
class ClassA {public void operationA() {System.out.println("执行A类操作");}
}// 子系统组件B
class ClassB {public void operationB() {System.out.println("执行B类操作");}
}// 统一外观接口
class Facade {private ClassA componentA = new ClassA();private ClassB componentB = new ClassB();public void unifiedOperation() {componentA.operationA();componentB.operationB();}
}// 使用示例
public class Client {public static void main(String[] args) {Facade gateway = new Facade();gateway.unifiedOperation();}
}


享元模式

定义:运用共享技术有效地支持大量细粒度的对象。

解释:享元模式通过运用共享技术有效地支持大量细粒度的对象。
核心机制

  • 分离内部状态(固有属性)与外部状态(可变属性)
  • 使用工厂管理共享对象池
  • 适用于存在大量重复对象的场景
// 抽象享元接口
interface Shape {void draw(int positionX, int positionY);
}// 具体享元对象
class Circle implements Shape {private String color;public Circle(String color) {this.color = color;}@Overridepublic void draw(int x, int y) {System.out.println("绘制" + color + "色圆形于(" + x + "," + y + ")");}
}// 对象工厂
class ShapeFactory {private Map<String, Shape> shapePool = new HashMap<>();public Shape getShape(String color) {if (!shapePool.containsKey(color)) {shapePool.put(color, new Circle(color));}return shapePool.get(color);}
}// 使用示例
public class Client {public static void main(String[] args) {ShapeFactory factory = new ShapeFactory();String[] colors = {"红", "蓝", "绿"};for(int i=0; i<10; i++){Shape shape = factory.getShape(colors[i%3]);shape.draw(i*10, i*5);}}
}


代理模式

定义:为其他对象提供一种代理以控制对这个对象的访问。

解释:代理模式通过为其他对象提供一种代理以控制对这个对象的访问。
典型应用

  • 远程访问代理
  • 权限控制代理
  • 延迟加载代理
// 服务接口
interface Database {void query(String sql);
}// 实际服务对象
class DatabaseServer implements Database {public void query(String sql) {System.out.println("执行查询:" + sql);}
}// 代理控制器
class ProxyServer implements Database {private DatabaseServer server;private String accessLevel;public ProxyServer(String accessLevel) {this.accessLevel = accessLevel;}private boolean checkAccess() {return "admin".equals(accessLevel);}@Overridepublic void query(String sql) {if(!checkAccess()){System.out.println("权限拒绝");return;}if(server == null){server = new DatabaseServer(); // 延迟加载}server.query(sql);}
}// 使用示例
public class Client {public static void main(String[] args) {Database proxy = new ProxyServer("user");proxy.query("SELECT * FROM users");Database adminProxy = new ProxyServer("admin");adminProxy.query("DELETE FROM logs");}
}


行为型模式

行为型模式主要关注对象之间的通信,通过定义对象之间的通信方式,来实现特定的行为。

解释器模式

定义:给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。

解释:解释器模式通过给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。
组成要素

  • 抽象表达式接口
  • 终结符表达式(基本元素)
  • 非终结符表达式(组合规则)
// 表达式接口
interface Expression {boolean evaluate(String context);
}// 基础表达式
class KeywordExpression implements Expression {private String keyword;public KeywordExpression(String word) {this.keyword = word;}@Overridepublic boolean evaluate(String text) {return text.contains(keyword);}
}// 组合表达式
class OrExpression implements Expression {private Expression left;private Expression right;public OrExpression(Expression left, Expression right) {this.left = left;this.right = right;}@Overridepublic boolean evaluate(String text) {return left.evaluate(text) || right.evaluate(text);}
}// 使用示例
public class Client {public static void main(String[] args) {Expression expr1 = new KeywordExpression("紧急");Expression expr2 = new KeywordExpression("重要");Expression complexExpr = new OrExpression(expr1, expr2);System.out.println(complexExpr.evaluate("本周会议内容"));  // falseSystem.out.println(complexExpr.evaluate("紧急通知!"));    // true}
}


模板方法模式

定义:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法的某些特定步骤。

解释:模板方法模式通过在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中,使得子类可以在不改变算法结构的情况下,重新定义算法的某些特定步骤。
设计要点

  1. 使用final修饰模板方法防止重写
  2. 抽象方法定义可变步骤
  3. 钩子方法实现流程控制
// 抽象类
abstract class AbstractClass {public final void templateMethod() {primitiveOperation1();primitiveOperation2();}protected abstract void primitiveOperation1();protected abstract void primitiveOperation2();
}// 具体子类A
class ConcreteClassA extends AbstractClass {protected void primitiveOperation1() {System.out.println("ConcreteClassA primitiveOperation1");}protected void primitiveOperation2() {System.out.println("ConcreteClassA primitiveOperation2");}
}// 具体子类B
class ConcreteClassB extends AbstractClass {protected void primitiveOperation1() {System.out.println("ConcreteClassB primitiveOperation1");}protected void primitiveOperation2() {System.out.println("ConcreteClassB primitiveOperation2");}
}// 客户端代码
public class Client {public static void main(String[] args) {AbstractClass abstractClass = new ConcreteClassA();abstractClass.templateMethod();abstractClass = new ConcreteClassB();abstractClass.templateMethod();}
}

以下是对四个设计模式的整理说明,采用标准技术文档格式呈现:

职责链模式

定义:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。

解释:职责链模式通过使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。

实现原理

  1. 抽象处理者定义处理接口和后续链接
  2. 具体处理者实现具体处理逻辑:
    • 能处理时直接处理
    • 不能处理时转给后继对象
  3. 客户端构建处理链
abstract class Handler {protected Handler next;public void setNext(Handler next) {this.next = next;}public abstract void process(int value);
}class RangeHandler extends Handler {private final int min;private final int max;public RangeHandler(int min, int max) {this.min = min;this.max = max;}@Overridepublic void process(int value) {if (value >= min && value <= max) {System.out.println("Processed by "+getClass().getSimpleName());} else if (next != null) {next.process(value);}}
}// 使用示例
Handler chain = new RangeHandler(0,10);
chain.setNext(new RangeHandler(11,20));
chain.setNext(new RangeHandler(21,30));
chain.process(25);

命令模式

定义:将一个请求封装为一个对象,从而使你可以用不同的请求、队列或者请求日志来参数化其他对象。命令模式也支持可撤销的操作。

解释:命令模式通过将一个请求封装为一个对象,从而使你可以用不同的请求、队列或者请求日志来参数化其他对象。命令模式也支持可撤销的操作。

核心组件

  • 命令接口:声明执行方法
  • 具体命令:绑定接收者与操作
  • 调用者:触发命令执行
  • 接收者:实际业务逻辑执行者
interface Command {void execute();void undo();
}class LightCommand implements Command {private final Light light;private boolean prevState;public LightCommand(Light light) {this.light = light;}@Overridepublic void execute() {prevState = light.isOn();light.toggle();}@Overridepublic void undo() {light.setState(prevState);}
}// 使用示例
RemoteControl remote = new RemoteControl();
remote.setCommand(new LightCommand(light));
remote.pressButton();

状态模式

定义:允许对象在内部状态改变时改变它的行为。对象看起来似乎修改了它的类。

解释:状态模式通过允许对象在内部状态改变时改变它的行为,使得对象看起来似乎修改了它的类。

实现要点

  1. 定义状态接口
  2. 实现具体状态类
  3. 上下文对象维护当前状态
interface State {void handle(Context context);
}class ActiveState implements State {@Overridepublic void handle(Context context) {System.out.println("Active processing");context.setState(new IdleState());}
}class Context {private State current;public void setState(State newState) {this.current = newState;}public void request() {current.handle(this);}
}

观察者模式

定义:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

解释:观察者模式通过定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

标准实现

// 抽象主题类
abstract 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 abstract void notifyObservers();
}// 抽象观察者类
interface Observer {void update();
}// 具体主题类
class ConcreteSubject extends Subject {private String state;public void setState(String state) {this.state = state;notifyObservers();}public String getState() {return state;}public void notifyObservers() {for (Observer observer : observers) {observer.update();}}
}// 具体观察者类
class ConcreteObserver implements Observer {private ConcreteSubject subject;public ConcreteObserver(ConcreteSubject subject) {this.subject = subject;}public void update() {if (subject.getState().equals("new state")) {System.out.println("ConcreteObserver's reaction");}}
}// 客户端代码
public class Client {public static void main(String[] args) {ConcreteSubject subject = new ConcreteSubject();Observer observer = new ConcreteObserver(subject);subject.attach(observer);subject.setState("new state");}
}
策略模式

定义:定义一系列算法,把它们一个个封装起来,并且使它们可互换。策略模式让算法的变化独立于使用算法的客户。

解释:策略模式通过定义一系列算法,把它们一个个封装起来,并且使它们可互换。策略模式让算法的变化独立于使用算法的客户。

结构解析

  1. 策略接口声明通用操作
  2. 具体策略类实现算法变体
  3. 上下文类维护策略引用并代理执行

Java实现

// 策略接口
interface Strategy {int doOperation(int num1, int num2);
}// 具体策略A
class OperationAdd implements Strategy {public int doOperation(int num1, int num2) {return num1 + num2;}
}// 具体策略B
class OperationSubtract implements Strategy {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 Client {public static void main(String[] args) {Context context = new Context(new OperationAdd());System.out.println("Result: " + context.executeStrategy(10, 5));context = new Context(new OperationSubtract());System.out.println("Result: " + context.executeStrategy(10, 5));}
}

访问者模式

定义:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

解释:访问者模式通过表示一个作用于某对象结构中的各元素的操作,使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

应用场景

  • 对象结构包含多个类
  • 需要动态添加新操作
  • 避免污染元素类接口

Java实现

// 抽象元素
abstract class Element {public abstract void accept(Visitor visitor);
}// 具体元素A
class ConcreteElementA extends Element {public void accept(Visitor visitor) {visitor.visit(this);}public void operationA() {System.out.println("ConcreteElementA operationA");}
}// 具体元素B
class ConcreteElementB extends Element {public void accept(Visitor visitor) {visitor.visit(this);}public void operationB() {System.out.println("ConcreteElementB operationB");}
}// 访问者接口
interface Visitor {void visit(ConcreteElementA element);void visit(ConcreteElementB element);
}// 具体访问者
class ConcreteVisitor implements Visitor {public void visit(ConcreteElementA element) {element.operationA();}public void visit(ConcreteElementB element) {element.operationB();}
}// 客户端代码
public class Client {public static void main(String[] args) {List<Element> elements = new ArrayList<>();elements.add(new ConcreteElementA());elements.add(new ConcreteElementB());Visitor visitor = new ConcreteVisitor();for (Element element : elements) {element.accept(visitor);}}
}
中介者模式

中介者模式提供了一个中介者对象,该对象封装了系统中对象间的交互方式,使各对象不需要显式地相互引用。这样可以减少类间的依赖,从而降低耦合度。

代码示例

// 中介者接口
interface Mediator {void registerComponent(Component component);void relayMessage(Component sender, String message);
}// 具体中介者
class ConcreteMediator implements Mediator {private List<Component> components = new ArrayList<>();@Overridepublic void registerComponent(Component component) {components.add(component);component.setMediator(this);}@Overridepublic void relayMessage(Component sender, String message) {for (Component component : components) {if (component != sender) {component.notify(message);}}}
}// 组件抽象类
abstract class Component {protected Mediator mediator;public void setMediator(Mediator mediator) {this.mediator = mediator;}public abstract void send(String message);public abstract void receive(String message);
}// 具体组件
class UserComponent extends Component {private String name;public UserComponent(String name) {this.name = name;}@Overridepublic void send(String message) {mediator.relayMessage(this, message);}@Overridepublic void receive(String message) {System.out.println(name + " received: " + message);}
}// 客户端代码
public class Client {public static void main(String[] args) {Mediator mediator = new ConcreteMediator();Component user1 = new UserComponent("User1");Component user2 = new UserComponent("User2");mediator.registerComponent(user1);mediator.registerComponent(user2);user1.send("Hello User2!");user2.send("Hi User1!");}
}

迭代器模式

迭代器模式提供了一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

代码示例

// 聚合接口
interface Aggregate {Iterator getIterator();
}// 具体聚合
class ConcreteAggregate implements Aggregate {private List<Object> items = new ArrayList<>();public void addItem(Object item) {items.add(item);}public Object getItem(int index) {return items.get(index);}@Overridepublic Iterator getIterator() {return new ConcreteIterator(this);}
}// 迭代器接口
interface Iterator {boolean hasNext();Object next();
}// 具体迭代器
class ConcreteIterator implements Iterator {private ConcreteAggregate aggregate;private int index = 0;public ConcreteIterator(ConcreteAggregate aggregate) {this.aggregate = aggregate;}@Overridepublic boolean hasNext() {return index < aggregate.items.size();}@Overridepublic Object next() {return aggregate.getItem(index++);}
}// 客户端代码
public class Client {public static void main(String[] args) {Aggregate aggregate = new ConcreteAggregate();aggregate.addItem("Item1");aggregate.addItem("Item2");aggregate.addItem("Item3");Iterator iterator = aggregate.getIterator();while (iterator.hasNext()) {System.out.println(iterator.next());}}
}

备忘录模式

备忘录模式在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

代码示例

// 备忘录接口
interface Memento {String getState();
}// 具体备忘录
class ConcreteMemento implements Memento {private String state;public ConcreteMemento(String state) {this.state = state;}@Overridepublic 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 ConcreteMemento(state);}public void getStateFromMemento(Memento memento) {state = memento.getState();}
}// 管理者
class Caretaker {private List<Memento> mementoList = new ArrayList<>();public void add(Memento state) {mementoList.add(state);}public Memento get(int index) {return mementoList.get(index);}
}// 客户端代码
public class Client {public static void main(String[] args) {Originator originator = new Originator();originator.setState("State1");Caretaker caretaker = new Caretaker();caretaker.add(originator.saveStateToMemento());originator.setState("State2");caretaker.add(originator.saveStateToMemento());originator.getStateFromMemento(caretaker.get(0));System.out.println(originator.getState()); // 输出:State1}
}

以上是设计模式的分类及说明,包括定义、解释和代码示例。这些模式在实际软件开发中有着广泛的应用,可以帮助开发者解决各种设计问题,提高代码的可维护性和可扩展性。

文章来源:https://blog.csdn.net/m0_74482103/article/details/148068411
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:https://dhexx.cn/news/show-5522242.html

相关文章

谷歌前CEO TED演讲解析:AI 红利的三年窗口期与行业重构

​谷歌前CEO埃里克施密特在2025年TED演讲中提出的"AI红利仅剩3年窗口期"观点&#xff0c;揭示了AI技术从算力、需求到监管的全局性变革。以下是基于演讲内容及关联数据的深度分析&#xff1a; 谷歌前CEO TED演讲解析&#xff1a;AI红利的三年窗口期与行业重构 一、算…

UniApp 实现的文件预览与查看功能#三方框架 #Uniapp

UniApp 实现的文件预览与查看功能 前言 在开发移动应用时&#xff0c;文件预览功能是一个非常常见的需求。无论是查看PDF文档、图片还是Office文件&#xff0c;都需要一个稳定且易用的预览解决方案。本文将详细介绍如何在UniApp中实现各类文件的预览功能&#xff0c;并分享一…

开发 前端搭建npm v11.4.0 is known not to run on Node.js v14.18.1.

错误nodejs 和npm 版本不一致 ERROR: npm v11.4.0 is known not to run on Node.js v14.18.1. This version of npm supports the following node versions: ^20.17.0 || >22.9.0. You can find the latest version at https://nodejs.org/. ERROR: D:\softTool\node-v14…

国标GB28181视频平台EasyGBS校园监控方案:多场景应用筑牢安全防线,提升管理效能

一、方案背景​ 随着校园规模不断扩大&#xff0c;传统监控系统因设备协议不兼容、数据分散管理&#xff0c;导致各系统之间相互独立、数据无法互通共享。在校园安全防范、教学管理以及应急响应过程中&#xff0c;这种割裂状态严重影响工作效率。国标GB28181软件EasyGBS视频云…

开源音视频转文字工具:基于 Vosk 和 Whisper 的多语言语音识别项目

背景介绍 随着短视频、播客等音视频内容的爆发式增长&#xff0c;快速将音视频内容转换为文字的需求也越来越大。无论是内容创作者需要的字幕&#xff0c;还是企业需要的会议记录&#xff0c;都需要一个可靠的语音转文字解决方案。 技术架构 本项目采用双引擎架构&#xff0…

电脑A和电脑B都无法ping通电脑C网络,电脑C可以ping通电脑A和B,使用新系统测试正常,排除硬件问题。

主要硬件&#xff1a;研华AIMB-705主板、i5-6500 C机在防火墙高级设置里启用以下两项规则后&#xff0c;A/B机可正常访问C机网络。&#xff08;直接关闭防火墙也可解决此问题&#xff09; 文件和打印机共享 (回显请求 - ICMPv4-In) 核心网络诊断 - ICMP 回显请求 (ICMPv4-In)…

安全强化的Linux

SElinux简介 SELinux是security-Enhanced Linux的缩写,意思是安全强化的linux SELinux主要由美国国家安全局(NSA)开发,当初开发的目的是为了避免资源的误用。传统的访问控制在我们开启权限后,系统进程可以直接访问 当我们对权限设置不严谨时,这种访问方式就是系统的安全漏洞 在…

MySQL故障排查

目录 一、MySQL 单实例故障排查 1. 连接类故障 2. 表损坏与权限故障 3. 其他常见故障 二、MySQL 主从故障排查 1. 基础配置问题 2. 数据同步异常 三、MySQL 性能优化策略 1. 硬件优化 2. 配置文件优化 3. SQL 优化 四、优化示例&#xff08;my.cnf 配置片段&#x…

MySQL 8.0 OCP 英文题库解析(五)

Oracle 为庆祝 MySQL 30 周年&#xff0c;截止到 2025.07.31 之前。所有人均可以免费考取原价245美元的MySQL OCP 认证。 从今天开始&#xff0c;将英文题库免费公布出来&#xff0c;并进行解析&#xff0c;帮助大家在一个月之内轻松通过OCP认证。 本期公布试题31~40 试题31:…

Eclipse Java 开发调优:如何让 Eclipse 运行更快?

Eclipse Java 开发调优&#xff1a;如何让 Eclipse 运行更快&#xff1f; 在 Java 开发领域&#xff0c;Eclipse 是一款被广泛使用的集成开发环境&#xff08;IDE&#xff09;。然而&#xff0c;随着项目的日益庞大和复杂&#xff0c;Eclipse 的运行速度可能会逐渐变慢&#x…