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

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

创建型模式

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

工厂方法模式

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

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

代码示例

// 产品接口
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}
}

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

相关文章:

  • Cursor日常配置指南
  • 【C++进阶篇】AVL树的实现(赋源码)
  • 元注解(Meta-Annotations)详解
  • 双条件拆分工作表,一键生成独立工作簿-Excel易用宝
  • Python将Excel单元格某一范围生成—截图(进阶版—带样式+批量+多级表头)
  • reserve学习笔记(花指令)
  • W3电力线载波通信技术
  • 项目删除了,为什么vscode中的git还是存在未提交记录,应该怎么删除掉
  • 系统安全应用
  • 系统安全及应用深度笔记
  • Android13 以太网(YT8531)
  • MetaERP:开启企业数字化管理新时代
  • 2025年渗透测试面试题总结-各厂商二面试题01(题目+回答)
  • 智能呼叫中心系统的功能
  • 设计模式-面试题
  • 用Caffeine和自定义注解+AOP优雅实现本地防抖接口限流
  • 基于RT-Thread的STM32F4开发第五讲——软件模拟I2C
  • spring boot 注解 @bean
  • 解决 uv run 时 ModuleNotFoundError: No module named ‘anthropic‘ 的完整指南
  • HTTPS、SSL证书是啥?网站“安全小锁”的入门科普
  • 国家发改委谈整治“内卷式”竞争:加力破除地方保护和市场分割,遏制落后产能无序扩张
  • “十五五”规划编制工作开展网络征求意见活动
  • 连续两个交易日涨停,华夏幸福:生产经营活动正常,不存在影响股价波动的重大事宜
  • 年内首次存款利率下调启动:3年期、5年期均下调0.25个百分点
  • 今晚油价下调,加满一箱油将省9元
  • 贯彻落实《生态环境保护督察工作条例》,充分发挥生态环境保护督察利剑作用