定义:备忘录模式又称为快照模式(Snapshot Pattern),在不破坏封装的前提下,捕获一个对象的内部状态,并将状态保存在对象之外,这样以后就可以将此对象恢复到初始保存的状态,类似于“后悔药”。属于行为型模式。
适用场景:
1)需要保存历史快照的场景;
2)希望在对象之外保存状态,且其他对象无法访问状态保存的具体内容;
角色:发起人,备忘录,备忘录管理者
代码演示
备忘录类
package com.lucifer.designpattern.memo;
import java.util.Date;
public class ArticleMemo {
private String title;
private String content;
private Date createTime;
public ArticleMemo(String title, String content, Date createTime) {
this.title = title;
this.content = content;
this.createTime = createTime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "ArticleMemo{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
", createTime=" + createTime +
'}';
}
}
编辑器类
package com.lucifer.designpattern.memo;
import java.util.Date;
public class Editor {
private String title;
private String content;
private Date createTime;
private DraftBox draftBox = DraftBox.getInstance();
public Editor(String title, String content, Date createTime) {
this.title = title;
this.content = content;
this.createTime = createTime;
}
public void saveToMemo() {
ArticleMemo memo = new ArticleMemo(this.title, this.content, this.createTime);
draftBox.addMemo(memo);
}
public void undoFromMemo() {
ArticleMemo memo = draftBox.getMemo();
this.title = memo.getTitle();
this.content = memo.getContent();
this.createTime = memo.getCreateTime();
}
@Override
public String toString() {
return "Editor{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
", createTime=" + createTime +
'}';
}
}
草稿箱类
package com.lucifer.designpattern.memo;
import java.util.Stack;
public class DraftBox {
private static DraftBox draftBox = new DraftBox();
private final Stack<ArticleMemo> STACK = new Stack<ArticleMemo>();
private DraftBox() {}
public static DraftBox getInstance() {
return draftBox;
}
public ArticleMemo getMemo() {
ArticleMemo memo = STACK.pop();
return memo;
}
public void addMemo(ArticleMemo memo) {
STACK.push(memo);
}
}
测试类
package com.lucifer.designpattern.memo;
import java.util.Date;
public class MemoTest {
public static void main(String[] args) {
Editor editor = new Editor("备忘录模式", "备忘录模式又称为快照模式(Snapshot Pattern)", new Date());
editor.saveToMemo();
System.out.println("第一次保存到草稿箱:" + editor.toString());
editor = new Editor("备忘录模式", "备忘录模式又称为快照模式(Snapshot Pattern),在不破坏封装的前提下,捕获一个对象的内部状态,并将状态保存在对象之外,这样以后就可以将此对象恢复到初始保存的状态,类似于“后悔药”。属于行为型模式。", new Date());
editor.saveToMemo();
System.out.println("第二次保存到草稿箱:" + editor.toString());
editor.undoFromMemo();
System.out.println("第一次撤回内容:" + editor.toString());
editor.undoFromMemo();
System.out.println("第二次撤回内容:" + editor.toString());
}
}
执行结果