本文節選自《設計模式就該這樣學》
1 使用備忘錄模式實現草稿箱功能
大家都用過網頁中的富文本編輯器,編輯器通常都會附帶草稿箱、撤銷等操作。下面用一段代碼來實現一個這樣的功能。假設,我們在GPer社區中發布一篇文章,文章編輯的過程需要花很長時間,中間也會不停地撤銷、修改,甚至可能要花好幾天才能寫出一篇精品文章,因此可能會將已經編輯好的內容實時保存到草稿箱。
首先創建發起人角色編輯器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 + '\'' +
'}';
}
}
然后創建備忘錄角色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 + '\'' +
'}';
}
}
接着創建備忘錄管理角色草稿箱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的一個子類,它實現了一個標准的后進先出的棧。如下表所示,主要定義了以下方法。
| 方法定義 | 方法描述 |
| -------- | -------- | -------- |
| boolean empty() | 測試堆棧是否為空 |
| Object peek( ) | 查看堆棧頂部的對象,但不從堆棧中移除它 |
| Object pop( ) | 移除堆棧頂部的對象,並作為此函數的值返回該對象 |
| Object push(Object element) | 把對象壓入堆棧頂部 |
| int search(Object element) | 返回對象在堆棧中的位置,以1為基數 |
最后編寫客戶端測試代碼。
public static void main(String[] args) {
DraftsBox draftsBox = new DraftsBox();
Editor editor = new Editor("我是這樣手寫Spring的,麻雀雖小五臟俱全",
"本文節選自《Spring5核心原理與30個類手寫實戰》一書,Tom著,電子工業出版社出版。",
"35576a9ef6fc407aa088eb8280fb1d9d.png");
ArticleMemento articleMemento = editor.saveToMemento();
draftsBox.addMemento(articleMemento);
System.out.println("標題:" + editor.getTitle() + "\n" +
"內容:" + editor.getContent() + "\n" +
"插圖:" + editor.getImgs() + "\n暫存成功");
System.out.println("完整的信息" + editor);
System.out.println("==========首次修改文章===========");
editor.setTitle("【Tom原創】我是這樣手寫Spring的,麻雀雖小五臟俱全");
editor.setContent("本文節選自《Spring5核心原理與30個類手寫實戰》一書,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("本文節選自《Spring5核心原理與30個類手寫實戰》一書,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次撤銷完成===========");
}
運行結果如下圖所示。
2 備忘錄模式在Spring源碼中的應用
備忘錄模式在框架源碼中的應用也是比較少的,主要還是結合具體的應用場景來使用。筆者在JDK源碼里一頓找,目前為止還是沒找到具體的應用,包括在MyBatis中也沒有找到對應的源碼。在Spring的Webflow源碼中還是找到一個StateManageableMessageContext接口,源碼如下。
public interface StateManageableMessageContext extends MessageContext {
public Serializable createMessagesMemento();
public void restoreMessages(Serializable messagesMemento);
public void setMessageSource(MessageSource messageSource);
}
我們看到有一個createMessagesMemento()方法,創建一個消息備忘錄。可以打開它的實現類,代碼如下。
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;
}
...
}
我們看到其主要邏輯就相當於給Message留一個備份,以備恢復之用。
關注微信公眾號『 Tom彈架構 』回復“設計模式”可獲取完整源碼。
本文為“Tom彈架構”原創,轉載請注明出處。技術在於分享,我分享我快樂!
如果本文對您有幫助,歡迎關注和點贊;如果您有任何建議也可留言評論或私信,您的支持是我堅持創作的動力。關注微信公眾號『 Tom彈架構 』可獲取更多技術干貨!