备忘录模式(Memento Pattern)保存一个对象的历史时期的一个数据备份,以便在业务需要的时候恢复对象。Windows 里的 ctrl + z,Idea的后退功能都是备忘录模式的具体体现。
一、需求举例:
项目代码开发中,经常会用到后退功能(即ctrl + z功能),恢复到代码的上一个版本。备忘录类负责保存历史版本的数据,备忘录管理类负责管理备忘录,从中恢复历史版本的数据,编写者类负责编写代码,并保存数据到备忘录。
二、类图:
三、代码实例:
1.代码备忘录类:CodeMemento
package com.lance.memento;
public class CodeMemento {
private String previousCode;
public String getPreviousCode() {
return previousCode;
}
public CodeMemento(String previousCode) {
this.previousCode = previousCode;
}
}
2.代码编写者类:CodeOriginator
package com.lance.memento;
public class CodeOriginator {
private String currentCode;
public String getCurrentCode() {
return currentCode;
}
public void setCurrentCode(String currentCode) {
this.currentCode = currentCode;
}
public CodeMemento createCodeMemento() {
return new CodeMemento(currentCode);
}
public void setCodeMemento(CodeMemento codeMemento) {
this.currentCode = codeMemento.getPreviousCode();
}
public void show() {
System.out.println("current code:" + this.currentCode);
}
}
3.备忘录管理类:CodeCareTaker,负责从 Memento 中恢复对象。
package com.lance.memento;
public class CodeCareTaker {
private CodeMemento codeMemento;
public CodeMemento getCodeMemento() {
return codeMemento;
}
public void setCodeMemento(CodeMemento codeMemento) {
this.codeMemento = codeMemento;
}
}
4.主类:
package com.lance.memento;
public class MementoPattern {
public static void main(String[] args) {
System.out.println("==========start==========");
CodeOriginator codeOriginator = new CodeOriginator();
codeOriginator.setCurrentCode("Java Hello World!");
System.out.println("step 1:");
codeOriginator.show();
CodeCareTaker codeCareTaker = new CodeCareTaker();
codeCareTaker.setCodeMemento(codeOriginator.createCodeMemento());
codeOriginator.setCurrentCode("Java Spring!");
System.out.println("step 2:");
codeOriginator.show();
codeOriginator.setCodeMemento(codeCareTaker.getCodeMemento());
System.out.println("rollback:");
codeOriginator.show();
System.out.println("==========end==========");
}
}
输出结果:
==========start==========
step 1:
current code:Java Hello World!
step 2:
current code:Java Spring!
rollback:
current code:Java Hello World!
==========end==========
网友评论