輕鬆掌握Java備忘錄模式_java

來源:互聯網
上載者:User

定義:儲存一個對象的某個狀態,以便在適當的時候恢複對象

特點:

    1、給使用者提供了一種可以恢複狀態的機制,可以使使用者能夠比較方便地回到某個曆史的狀態。

    2、實現了資訊的封裝,使得使用者不需要關心狀態的儲存細節。

企業級應用和常用架構中的應用:常見文字編輯器使用了該模式

執行個體:

注意:該執行個體中只有撤銷操作,沒有向前還原作業

/** * 目標對象:將要被備忘的對象 */class Word { private String content; private String image; private String table; public Word(String content, String image, String table) { super(); this.content = content; this.image = image; this.table = table; }  public WordMemento memento(){ return new WordMemento(this); }  public void recovery(WordMemento memento){ this.content = memento.getContent(); this.image = memento.getImage(); this.table = memento.getTable(); }  public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getTable() { return table; } public void setTable(String table) { this.table = table; }}/** * 備忘錄對象 */class WordMemento{ private String content; private String image; private String table;  public WordMemento(Word word) { this.content = word.getContent(); this.image = word.getImage(); this.table = word.getTable(); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getTable() { return table; } public void setTable(String table) { this.table = table; }}/** * 負責人對象:負責記錄備忘錄對象 */class CareTaker{ private List<WordMemento> list = new ArrayList<>(); private int index = 0;  public void setMemento(WordMemento memento){ list.add(memento); this.index = list.size(); }  public WordMemento getWordMemento(){ if(index == 0){  System.out.println("沒有可還原的內容");  return null; } WordMemento memento = list.get(index-1); list.remove(index-1); index--; return memento; }}

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.