19) Memento pattern
类别:
Behavioral Pattern (备忘录模式)
问题:
方案:
示例:
import java.util.ArrayList; import java.util.List; public class MementoPatternDemo { public static void main(String[] args) { Scene scene = new Scene(); List<Memento> mementoList = new ArrayList<Memento>(); scene.setState("State #1"); scene.setState("State #2"); mementoList.add(scene.snapshootToMemento()); scene.setState("State #3"); mementoList.add(scene.snapshootToMemento()); scene.setState("State #4"); System.out.println("Current State: " + scene.getState()); scene.recoverFromMemento(mementoList.get(0)); System.out.println("First saved State: " + scene.getState()); scene.recoverFromMemento(mementoList.get(1)); System.out.println("Second saved State: " + scene.getState()); } } class Memento { private String state; public Memento(String state) { this.state = state; } public String getState() { return state; } } class Scene { private String state; public void setState(String state) { this.state = state; } public String getState() { return state; } public Memento snapshootToMemento() { return new Memento(state); } public void recoverFromMemento(Memento Memento) { state = Memento.getState(); } }
Current State: State #4 First saved State: State #2 Second saved State: State #3
应用:
不足:(
优化:)