设计模式学习—备忘录模式(Memento Design Pattern)

xiaoxiao2021-02-28  3

一、我的理解

备忘录模式用于存储某个类在某一时刻的状态。

二、实现方式

另外创建一个类Memento用于保存目标类的状态信息,然后由另一类来存储和管理这一系列保存的状态

三、实例

Java实例
Originator类:原始类,对该类的状态进行保存 package com.study.dp.memento; public class Originator { private String state; public String getState() { return state; } public void setState(String state) { this.state = state; } public Memento saveStateToMemento() { return new Memento(state); } public void getStateFromMemento(Memento memento) { this.state = memento.getState(); } }Memento类:备忘录类,保存目标类的状态信息 package com.study.dp.memento; public class Memento { private String state; public Memento(String state) { super(); this.state = state; } public String getState() { return state; } }CareTaker类:备忘录管理类,存储和管理备忘录 package com.study.dp.memento; import java.util.ArrayList; import java.util.List; public 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); } }Demo类:测试 package com.study.dp.memento; public class Demo { public static void main(String[] args) { Originator originator = new Originator(); CareTaker careTaker = new CareTaker(); originator.setState("State #1"); originator.setState("State #2"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #3"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #4"); System.out.println("Current State: "+originator.getState()); originator.getStateFromMemento(careTaker.get(0)); System.out.println("First saved State: "+originator.getState()); originator.getStateFromMemento(careTaker.get(1)); System.out.println("Second saved State: "+originator.getState()); } }

四、应用场景

转载请注明原文地址: https://www.6miu.com/read-850087.html

最新回复(0)