目录
前言
UML
plantuml
类图
实战代码
模板
Originator
Memento
CareTaker
Client
前言
使用备忘录模式,主要目的就是创建对象副本,保存对象内部状态的的快照,以便在需要时恢复对象至某一个历史状态。
仅仅从创建副本来看,备忘录模式和原型模式其实没啥区别,不过备忘录模式是行为型设计模式,重点在于恢复对象到某一历史状态。
备忘录模式下,总共有三个角色,原始对象 Originator,对象快照 Memento,以及管理它们的 CareTaker
UML
plantuml
@startuml 'https://plantuml.com/class-diagramclass Originator {- attr : type+ createMemento() : Memento+ restore(Memento) : void }class Memento {- attr : type }class CareTaker {- originator : Originator- mementos : List<Memento>+ createMemento() : void+ restore(int) : void }class Client {}Originator ..> Memento CareTaker "1" --> "1" Originator CareTaker "1" --> "n" MementoClient --> CareTaker Client --> Originator@enduml
类图
实战代码
模板
Originator
class Originator {String state;Originator(String state) {this.state = state;}public String getState() {return state;}public void setState(String state) {this.state = state;}public Memento createMemento() {Memento memento = new Memento();memento.setState(this.state);return memento;}public void restore(Memento memento) {this.state = memento.getState();}
}
Memento
public class Memento {private String state;public String getState() {return state;}public void setState(String state) {this.state = state;}
}
CareTaker
class CareTaker {Originator originator;List<Memento> mementos;CareTaker(Originator originator) {this.originator = originator;mementos = new ArrayList<>();}public void createMemento() {Memento memento = this.originator.createMemento();mementos.add(memento);}public void restore(int index) {this.originator.restore(mementos.get(index));}
}
Client
public class Client {public static void main(String[] args) {Originator originator = new Originator("init");CareTaker careTaker = new CareTaker(originator);System.out.println(originator.getState());careTaker.createMemento();originator.setState("run");careTaker.createMemento();System.out.println(originator.getState());careTaker.restore(0);System.out.println(originator.getState());}
}