本文共 2054 字,大约阅读时间需要 6 分钟。
备忘录模式(Memento Pattern)保存一个对象的某个状态,以便在适当的时候恢复对象。备忘录模式属于行为型模式。
备忘录模式使用三个类 Memento、Originator 和 CareTaker。Memento 包含了要被恢复的对象的状态。Originator 创建并在 Memento 对象中存储状态。Caretaker 对象负责从 Memento 中恢复对象的状态。
MementoPatternDemo,我们的演示类使用 CareTaker 和 Originator 对象来显示对象的状态恢复。步骤 1创建 Memento 类。Memento.javapublic class Memento { private String state; public Memento(String state){ this.state = state; } public String getState(){ return state; } }步骤 2创建 Originator 类。Originator.javapublic class Originator { private String state; public void setState(String state){ this.state = state; } public String getState(){ return state; } public Memento saveStateToMemento(){ return new Memento(state); } public void getStateFromMemento(Memento Memento){ state = Memento.getState(); }}步骤 3创建 CareTaker 类。CareTaker.javaimport java.util.ArrayList;import java.util.List;public class CareTaker { private ListmementoList = new ArrayList (); public void add(Memento state){ mementoList.add(state); } public Memento get(int index){ return mementoList.get(index); }}步骤 4使用 CareTaker 和 Originator 对象。MementoPatternDemo.javapublic class MementoPatternDemo { 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()); }}步骤 5验证输出。Current State: State #4First saved State: State #2Second saved State: State #3
转载地址:http://rhbfx.baihongyu.com/