核心模块:Originator原发器、Mementor备忘录、Caretaker负责人
所有代码请访问:git@code.aliyun.com:289804201/PatternLearn.git
使用场景:大多数编辑器,提供undo的操作功能;
优点:实现了信息的封装,不破坏封装的情况下,保存内部状态,用户不需要关心保存细节;
缺点:内部成员变量过多,保存的内容过多,耗费系统资源;
注意:
1,Mementor的具体的保存操作只允许Originator访问;
2,CareTaker保存原发器的操作,可以只有一个节点或者一个队列、栈;
/**
* Created by tory on 2017/12/11.
* 备忘录模式
* 提供一种状态操作恢复模式,大多数的undo操作都是这种模式
*/
public class MementoPattern {
public static void main(String[] args) {
RoleCaretaker caretaker = new RoleCaretaker();
Role soldier = new Role("tory", "1000");
soldier.show();
caretaker.setMemeto(soldier.save());
soldier.updateBlood("900");
soldier.show();
caretaker.setMemeto(soldier.save());
soldier.updateAddr("school");
soldier.updateBlood("800");
soldier.show();
caretaker.setMemeto(soldier.save());
System.out.print("now we will back\n");
soldier.restore(caretaker.getMemeto());
soldier.show();
soldier.restore(caretaker.getMemeto());
soldier.show();
soldier.restore(caretaker.getMemeto());
soldier.show();
soldier.restore(caretaker.getMemeto());
soldier.show();
}
}
//Originator 原发器
class Role {
private String name;
private String blood;
private String addr;
Role(String name, String blood) {
this.name = name;
this.blood = blood;
this.addr = "base";
}
public void updateBlood(String blood) {
this.blood = blood;
}
public void updateAddr(String addr) {
this.addr = addr;
}
public void show() {
System.out.println(name + "'s blood is " + blood + " in " + addr);
}
//产生副本
public RoleMemento save() {
return new RoleMemento(blood, addr);
}
//从副本恢复
public void restore(RoleMemento memento) {
if (null != memento) {
this.blood = memento.blood;
this.addr = memento.addr;
}
}
}
//Memento 备忘录,原发器的副本
class RoleMemento {
//这里副本只存血量和地址
String blood;
String addr;
RoleMemento(String blood, String addr) {
this.blood = blood;
this.addr = addr;
}
}
//Caretaker 负责人,保存原发器的一个或者一连串的动作
class RoleCaretaker {
Stack<RoleMemento> stack = new Stack<>();
//保存副本
public void setMemeto(RoleMemento memeto) {
stack.push(memeto);
}
//取出副本
public RoleMemento getMemeto() {
if (!stack.empty()) {
return stack.pop();
}
return null;
}
}
内容打印
Hello World!
tory's blood is 1000 in base
tory's blood is 900 in base
tory's blood is 800 in school
now we will back
tory's blood is 800 in school
tory's blood is 900 in base
tory's blood is 1000 in base
tory's blood is 1000 in base