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

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

创建型模式

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

工厂方法模式

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

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

代码示例

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

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

相关文章:

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

创建型模式 创建型模式主要关注对象的创建过程&#xff0c;旨在通过不同的方式创建对象&#xff0c;以满足不同的需求。 工厂方法模式 定义&#xff1a;定义一个创建对象的接口&#xff0c;让子类决定实例化哪一个类。 解释&#xff1a;工厂方法模式通过定义一个创建对象的…...

Chromium 浏览器核心生命周期剖析:从 BrowserProcess 全局管理到 Browser 窗口实例

在 Chromium 浏览器架构中&#xff0c;BrowserProcess 和 Browser 是两个核心类&#xff0c;分别管理 浏览器进程的全局状态 和 单个浏览器窗口的实例。它们的生命周期设计直接影响浏览器的稳定性和资源管理。以下是它们的详细生命周期分析&#xff1a; 1. BrowserProcess 的生…...

易境通海外仓系统:一件代发全场景数字化解决方案

随着全球经济一体化和消费升级&#xff0c;一件代发业务的跨境电商市场规模持续增长。然而&#xff0c;一件代发的跨境运营也面临挑战&#xff0c;传统海外仓管理模式更因效率低下、协同困难成为业务扩张的瓶颈。 一、一件代发跨境运营痛点 1、多平台协同&#xff1a;卖家往往…...

Flink 非确定有限自动机NFA

Flink 是一个用于状态化计算的分布式流处理框架&#xff0c;而非确定有限自动机&#xff08;NFA, Non-deterministic Finite Automaton&#xff09;是一种在计算机科学中广泛使用的抽象计算模型&#xff0c;常用于正则表达式匹配、模式识别等领域。 Apache Flink 提供了对 NFA…...

YoloV9改进策略:卷积篇|风车卷积|即插即用

论文信息 论文标题:《Pinwheel-shaped Convolution and Scale-based Dynamic Loss for Infrared Small Target Detection》 论文链接:https://arxiv.org/pdf/2412.16986 GitHub链接:https://github.com/JN-Yang/PConv-SDloss-Data 论文翻译 摘要 https://arxiv.org/pd…...

【Python训练营打卡】day30 @浙大疏锦行

DAY 30 模块和库的导入 知识点回顾&#xff1a; 1. 导入官方库的三种手段 2. 导入自定义库/模块的方式 3. 导入库/模块的核心逻辑&#xff1a;找到根目录&#xff08;python解释器的目录和终端的目录不一致&#xff09; 作业&#xff1a;自己新建几个不同路径文件尝试下如何…...

超越想象:利用MetaGPT打造高效的AI协作环境

前言 在人工智能迅速发展的今天&#xff0c;如何让多个大语言模型&#xff08;LLM&#xff09;高效协同工作成为关键挑战。MetaGPT 作为一种创新的多智能体框架&#xff0c;成功模拟了一个真实软件公司的运作流程&#xff0c;实现了从需求分析到代码实现的全流程自动化&#x…...

仿腾讯会议——添加音频

1、实现开启或关闭音频 2、 定义信号 3、实现开始暂停音频 4、实现信号槽连接 5、回收资源 6、初始化音频视频 7、 完成为每个人创建播放音频的对象 8、发送音频 使用的是对象ba&#xff0c;这样跨线程不会立刻回收&#xff0c;如果使用引用&#xff0c;跨线程会被直接回收掉&a…...

虚幻引擎5-Unreal Engine笔记之`GameMode`、`关卡(Level)` 和 `关卡蓝图(Level Blueprint)`的关系

虚幻引擎5-Unreal Engine笔记之GameMode、关卡&#xff08;Level&#xff09; 和 关卡蓝图&#xff08;Level Blueprint&#xff09;的关系 code review! 参考笔记&#xff1a; 1.虚幻引擎5-Unreal Engine笔记之GameMode、关卡&#xff08;Level&#xff09; 和 关卡蓝图&…...

vue3 vite 项目中自动导入图片

vue3 vite 项目中自动导入图片 安装插件配置插件使用方法 安装插件 yarn add vite-plugin-vue-images -D 或者 npm install vite-plugin-vue-images -D配置插件 在 vite.config.js 文件中配置插件 // 引入 import ViteImages from vite-plugin-vue-images;plugins: [vue(),/…...

MTK zephyr平台:系统休眠流程

一、概述: 当内核没有需要调度的东西时,就会进入空闲状态。 CONFIG_PM=y时允许内核调用PM subsys,将空闲系统置于支持的电源状态之一。 Application负责设置唤醒事件,该事件通常是由SoC外围模块触发的中断,例如: SysTick、RTC、计数器、GPIO 并非所有外设在所有电源模式…...

涨薪技术|0到1学会性能测试第71课-T-SQL调优

前面的推文我们掌握了索引调优技术,今天给大家分享T-SQL调优技术。后续文章都会系统分享干货,带大家从0到1学会性能测试。 对T-SQL语句进行调校是DBA调优数据库性能的主要任务,因为不同的查询语句,即使查询出来的结果一致,其消耗的时间和系统资源也有所不同,所以如何使查…...

Spark SQL 之 Antlr grammar 具体分析

src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseLexer.g4 BACKQUOTED_IDENTIFIER: ` ( ~` | `` )* `;src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4 queryPrimary:...

Python----目标检测(PASCAL VOC数据集)

一、PASCAL VOC数据集 PASCAL VOC&#xff08;Visual Object Classes&#xff09;数据集是计算机视觉领域中广泛使用的一个 标准数据集&#xff0c;用于目标检测、图像分割、图像分类、动作识别等任务。该数据集由 PASCAL&#xff08;Pattern Analysis, Statistical Modelling …...

LabVIEW汽车CAN总线检测系统开发

CAN&#xff08;ControllerArea Network&#xff09;总线作为汽车电子系统的核心通信协议&#xff0c;广泛应用于动力总成、车身控制、辅助驾驶等系统。基于 LabVIEW 开发 CAN 总线检测系统&#xff0c;可充分利用其图形化编程优势、丰富的硬件接口支持及强大的数据分析能力&am…...

MySQL数据库基础 -- SQL 语句的分类,存储引擎

目录 1. 什么是数据库 2. 基本使用 2.1 进入 mysql 2.2 服务器、数据库以及表的关系 2.3 使用案例 2.4 数据逻辑存储 3. SQL 语句分类 4. 存储引擎 4.1 查看存储引擎 4.2 存储引擎的对比 1. 什么是数据库 安装完 MySQL 之后&#xff0c;会有 mysql 和 mysqld。 MySQL …...

二元Logistic回归

二元Logistic回归 在机器学习领域&#xff0c;二元Logistic回归是一种非常经典的分类模型&#xff0c;广泛用于解决具有两类标签的分类问题。Logistic回归通过逻辑函数&#xff08;Sigmoid函数&#xff09;将预测结果映射到概率值&#xff0c;并进行分类。 一、Logistic回归 …...

如何从容应对面试?

引言 简历通过了&#xff0c;终于获得这次来之不易面试机会的你&#xff0c;是不是又在思考以下问题&#xff1a;基本礼仪都包括哪些方面&#xff1f;如何在群面中打动面试官&#xff1f;有什么注意事项&#xff1f;在面试的过程中&#xff0c;我们不单单要懂得面试技巧&#…...

如何使用GIT管理项目代码

介绍 ​ Git是目前世界上最流行甚至最好的开源分布式版本控制系统&#xff0c;不论是很小的项目还是很大的项目&#xff0c;它都能有效并且高效的处理项目版本管理&#xff0c;初衷是为了帮助管理linux内核代码而开发的一个开放源码的版本控制软件。 GIT常用分支名称 分支分…...

RHCE 练习三:架设一台 NFS 服务器

一、题目要求 1、开放 /nfs/shared 目录&#xff0c;供所有用户查询资料 2、开放 /nfs/upload 目录&#xff0c;为 192.168.xxx.0/24 网段主机可以上传目录&#xff0c;并将所有用户及所属的组映射为 nfs-upload,其 UID 和 GID 均为 210 3.将 /home/tom 目录仅共享给 192.16…...

【android bluetooth 协议分析 01】【HCI 层介绍 9】【ReadLocalSupportedCommands命令介绍】

1. HCI_Read_Local_Supported_Commands 命令介绍 1. 命令介绍&#xff08;Description&#xff09; HCI_Read_Local_Supported_Commands 是 HCI 层中非常重要的查询命令。它允许 Host&#xff08;如 Android 系统中的 Bluetooth stack&#xff09;获取 Controller&#xff08;…...

stm32实战项目:无刷驱动

目录 系统时钟配置 PWM模块初始化 ADC模块配置 霍尔接口配置 速度环定时器 换相逻辑实现 主控制循环 系统时钟配置 启用72MHz主频&#xff1a;RCC_Configuration()设置PLL外设时钟使能&#xff1a;TIM1/ADC/GPIO时钟 #include "stm32f10x.h"void RCC_Configu…...

python打卡训练营打卡记录day30

一、导入官方库 我们复盘下学习python的逻辑&#xff0c;所谓学习python就是学习python常见的基础语法学习你所处理任务需要用到的第三方库。 1.1标准导入&#xff1a;导入整个库 这是最基本也是最常见的导入方式&#xff0c;直接使用import语句。 # 方式1&#xff1a;导入整…...

2025年- H33-Lc141 --148. 排序链表(快慢指针,快指针先出发一步)--Java版

1.题目描述 2.思路 时间空间复杂度分别为 O(nlogn) 和 O(1)&#xff0c;根据时间复杂度想到二分法&#xff0c;从而联想到归并排序&#xff1b;对数组做归并排序的空间复杂度为 O(n)&#xff0c;分别由新开辟数组 O(n) 和递归函数调用 O(logn) 组成&#xff0c;而根据链表特性…...

【prometheus+Grafana篇】基于Prometheus+Grafana实现Oracle数据库的监控与可视化

&#x1f4ab;《博主主页》&#xff1a; &#x1f50e; CSDN主页 &#x1f50e; IF Club社区主页 &#x1f525;《擅长领域》&#xff1a;擅长阿里云AnalyticDB for MySQL(分布式数据仓库)、Oracle、MySQL、Linux、prometheus监控&#xff1b;并对SQLserver、NoSQL(MongoDB)有了…...

板凳-------Mysql cookbook学习 (四)

综合对比与选择建议 维度 PHP Java Python Ruby Perl 学习门槛 低&#xff08;适合新手&#xff09; 高&#xff08;语法复杂&#xff09; 低&#xff08;语法简洁&#xff09; 中&#xff08;需理解 Rails 理念&#xff09; 中&#xff08;特殊语法&#xf…...

【D1,2】 贪心算法刷题

文章目录 不同路径 II整数拆分 不同路径 II 初始化的时候不能整列初始化为1&#xff0c;因为如果有障碍物&#xff0c;后面的都不能到达 也不能整列初始化为0&#xff0c;因为状态转移的时候第一行第一列都没有检查&#xff0c;因此不能部分初始化 整数拆分 需要考虑几种情况…...

算法题(150):拼数

审题&#xff1a; 本题需要我们将数组中的数据经过排序&#xff0c;使得他们拼接后得到的数是所有拼接方案中最大的 思路&#xff1a; 方法一&#xff1a;排序贪心 贪心策略1&#xff1a;直接排序 如果我们直接按照数组数据的字典序进行排序&#xff0c;会导致部分情况出错 eg&…...

Denoising Score Matching with Langevin Dynamics

在自然图像等复杂数据集中&#xff0c;真实数据往往集中分布在一个低维流形上&#xff0c;概率密度函数的梯度&#xff08;即得分函数&#xff09;难以定义与估计。为缓解该问题&#xff0c;SMLD 提出使用不同强度的高斯噪声对数据进行扰动&#xff0c;扰动后的数据不再集中于低…...

Docker构建 Dify 应用定时任务助手

概述 Dify 定时任务管理工具是一个基于 GitHub Actions 的自动化解决方案&#xff0c;用于实现 Dify Workflow 的定时执行和状态监控。无需再为缺乏定时任务支持而感到困扰&#xff0c;本工具可以帮助设置自动执行任务并获取实时通知&#xff0c;优化你的工作效率。 注意&…...