本文節(jié)選自《設(shè)計(jì)模式就該這樣學(xué)》
1 使用備忘錄模式實(shí)現(xiàn)草稿箱功能
大家都用過(guò)網(wǎng)頁(yè)中的富文本編輯器,編輯器通常都會(huì)附帶草稿箱、撤銷等操作。下面用一段代碼來(lái)實(shí)現(xiàn)一個(gè)這樣的功能。假設(shè),我們?cè)贕Per社區(qū)中發(fā)布一篇文章,文章編輯的過(guò)程需要花很長(zhǎng)時(shí)間,中間也會(huì)不停地撤銷、修改,甚至可能要花好幾天才能寫出一篇精品文章,因此可能會(huì)將已經(jīng)編輯好的內(nèi)容實(shí)時(shí)保存到草稿箱。
首先創(chuàng)建發(fā)起人角色編輯器Editor類。
public class Editor {
private String title;
private String content;
private String imgs;
public Editor(String title, String content, String imgs) {
this.title = title;
this.content = content;
this.imgs = imgs;
}
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 String getImgs() {
return imgs;
}
public void setImgs(String imgs) {
this.imgs = imgs;
}
public ArticleMemento saveToMemento() {
ArticleMemento articleMemento = new ArticleMemento(this.title,this.content,this.imgs);
return articleMemento;
}
public void undoFromMemento(ArticleMemento articleMemento) {
this.title = articleMemento.getTitle();
this.content = articleMemento.getContent();
this.imgs = articleMemento.getImgs();
}
@Override
public String toString() {
return "Editor{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
", imgs='" + imgs + '\'' +
'}';
}
}
然后創(chuàng)建備忘錄角色ArticleMemento類。
public class ArticleMemento {
private String title;
private String content;
private String imgs;
public ArticleMemento(String title, String content, String imgs) {
this.title = title;
this.content = content;
this.imgs = imgs;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
public String getImgs() {
return imgs;
}
@Override
public String toString() {
return "ArticleMemento{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
", imgs='" + imgs + '\'' +
'}';
}
}
接著創(chuàng)建備忘錄管理角色草稿箱DraftsBox類。
public class DraftsBox {
private final Stack<ArticleMemento> STACK = new Stack<ArticleMemento>();
public ArticleMemento getMemento() {
ArticleMemento articleMemento= STACK.pop();
return articleMemento;
}
public void addMemento(ArticleMemento articleMemento) {
STACK.push(articleMemento);
}
}
草稿箱中定義的Stack類是Vector的一個(gè)子類,它實(shí)現(xiàn)了一個(gè)標(biāo)準(zhǔn)的后進(jìn)先出的棧。如下表所示,主要定義了以下方法。
| 方法定義 | 方法描述 |
| -------- | -------- | -------- |
| boolean empty() | 測(cè)試堆棧是否為空 |
| Object peek( ) | 查看堆棧頂部的對(duì)象,但不從堆棧中移除它 |
| Object pop( ) | 移除堆棧頂部的對(duì)象,并作為此函數(shù)的值返回該對(duì)象 |
| Object push(Object element) | 把對(duì)象壓入堆棧頂部 |
| int search(Object element) | 返回對(duì)象在堆棧中的位置,以1為基數(shù) |
最后編寫客戶端測(cè)試代碼。
public static void main(String[] args) {
DraftsBox draftsBox = new DraftsBox();
Editor editor = new Editor("我是這樣手寫Spring的,麻雀雖小五臟俱全",
"本文節(jié)選自《Spring5核心原理與30個(gè)類手寫實(shí)戰(zhàn)》一書,Tom著,電子工業(yè)出版社出版。",
"35576a9ef6fc407aa088eb8280fb1d9d.png");
ArticleMemento articleMemento = editor.saveToMemento();
draftsBox.addMemento(articleMemento);
System.out.println("標(biāo)題:" + editor.getTitle() + "\n" +
"內(nèi)容:" + editor.getContent() + "\n" +
"插圖:" + editor.getImgs() + "\n暫存成功");
System.out.println("完整的信息" + editor);
System.out.println("==========首次修改文章===========");
editor.setTitle("【Tom原創(chuàng)】我是這樣手寫Spring的,麻雀雖小五臟俱全");
editor.setContent("本文節(jié)選自《Spring5核心原理與30個(gè)類手寫實(shí)戰(zhàn)》一書,Tom著");
System.out.println("==========首次修改文章完成===========");
System.out.println("完整的信息" + editor);
articleMemento = editor.saveToMemento();
draftsBox.addMemento(articleMemento);
System.out.println("==========保存到草稿箱===========");
System.out.println("==========第2次修改文章===========");
editor.setTitle("手寫Spring");
editor.setContent("本文節(jié)選自《Spring5核心原理與30個(gè)類手寫實(shí)戰(zhàn)》一書,Tom著");
System.out.println("完整的信息" + editor);
System.out.println("==========第2次修改文章完成===========");
System.out.println("==========第1次撤銷===========");
articleMemento = draftsBox.getMemento();
editor.undoFromMemento(articleMemento);
System.out.println("完整的信息" + editor);
System.out.println("==========第1次撤銷完成===========");
System.out.println("==========第2次撤銷===========");
articleMemento = draftsBox.getMemento();
editor.undoFromMemento(articleMemento);
System.out.println("完整的信息" + editor);
System.out.println("==========第2次撤銷完成===========");
}
運(yùn)行結(jié)果如下圖所示。

2 備忘錄模式在Spring源碼中的應(yīng)用
備忘錄模式在框架源碼中的應(yīng)用也是比較少的,主要還是結(jié)合具體的應(yīng)用場(chǎng)景來(lái)使用。筆者在JDK源碼里一頓找,目前為止還是沒(méi)找到具體的應(yīng)用,包括在MyBatis中也沒(méi)有找到對(duì)應(yīng)的源碼。在Spring的Webflow源碼中還是找到一個(gè)StateManageableMessageContext接口,源碼如下。
public interface StateManageableMessageContext extends MessageContext {
public Serializable createMessagesMemento();
public void restoreMessages(Serializable messagesMemento);
public void setMessageSource(MessageSource messageSource);
}
我們看到有一個(gè)createMessagesMemento()方法,創(chuàng)建一個(gè)消息備忘錄??梢源蜷_它的實(shí)現(xiàn)類,代碼如下。
public class DefaultMessageContext implements StateManageableMessageContext {
private static final Log logger = LogFactory.getLog(DefaultMessageContext.class);
private MessageSource messageSource;
@SuppressWarnings("serial")
private Map<Object, List<Message>> sourceMessages =
new AbstractCachingMapDecorator<Object, List<Message>>(
new LinkedHashMap<Object, List<Message>>()) {
protected List<Message> create(Object source) {
return new ArrayList<Message>();
}
};
...
public void clearMessages() {
sourceMessages.clear();
}
// implementing state manageable message context
public Serializable createMessagesMemento() {
return new LinkedHashMap<Object, List<Message>>(sourceMessages);
}
@SuppressWarnings("unchecked")
public void restoreMessages(Serializable messagesMemento) {
sourceMessages.putAll((Map<Object, List<Message>>) messagesMemento);
}
public void setMessageSource(MessageSource messageSource) {
if (messageSource == null) {
messageSource = new DefaultTextFallbackMessageSource();
}
this.messageSource = messageSource;
}
...
}
我們看到其主要邏輯就相當(dāng)于給Message留一個(gè)備份,以備恢復(fù)之用。
關(guān)注『 Tom彈架構(gòu) 』回復(fù)“設(shè)計(jì)模式”可獲取完整源碼。
【推薦】Tom彈架構(gòu):30個(gè)設(shè)計(jì)模式真實(shí)案例(附源碼),挑戰(zhàn)年薪60W不是夢(mèng)
本文為“Tom彈架構(gòu)”原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處。技術(shù)在于分享,我分享我快樂(lè)!
如果本文對(duì)您有幫助,歡迎關(guān)注和點(diǎn)贊;如果您有任何建議也可留言評(píng)論或私信,您的支持是我堅(jiān)持創(chuàng)作的動(dòng)力。關(guān)注『 Tom彈架構(gòu) 』可獲取更多技術(shù)干貨!