设计模式:备忘录模式(Memento)
歡迎支持筆者新作:《深入理解Kafka:核心設(shè)計(jì)與實(shí)踐原理》和《RabbitMQ實(shí)戰(zhàn)指南》,同時(shí)歡迎關(guān)注筆者的微信公眾號(hào):朱小廝的博客。
歡迎跳轉(zhuǎn)到本文的原文鏈接:https://honeypps.com/design_pattern/memento/
在不破壞封裝性的前提下,捕獲一個(gè)對(duì)象的內(nèi)部狀態(tài),并在該對(duì)象之外保存這個(gè)狀態(tài)。這樣以后就可將對(duì)象恢復(fù)到原先保存的狀態(tài)。
備忘錄模式的角色:
典型的備忘錄代碼:
public class Memento {private String state;public Memento(Oraginator o){state = o.state;}public void setState(String state){this.state = state;}public String getState(){return this.state;} }##案例
大家一般都玩過(guò)游戲吧,就算沒(méi)玩過(guò)游戲也見(jiàn)過(guò)室友、朋友玩過(guò)游戲吧。很多游戲中需要存檔,保存當(dāng)前的血條和魔法值,以防再挑戰(zhàn)boss的時(shí)候die了可以重新讀檔。
1 原發(fā)器Originator
2 備忘錄Memento
public class Memento {private int bloodValue;private int magicValue;public int getBloodValue(){return bloodValue;}public void setBloodValue(int bloodValue){this.bloodValue = bloodValue;}public int getMagicValue(){return magicValue;}public void setMagicValue(int magicValue){this.magicValue = magicValue;}public Memento(int bloodValue, int magicValue){this.bloodValue = bloodValue;this.magicValue = magicValue;} }3 負(fù)責(zé)人Caretaker
public class Caretaker {private Memento memento;public Memento getMemento(){return memento;}public void setMemento(Memento memento){this.memento = memento;} }4 測(cè)試代碼
Originator originator = new Originator(100,100);System.out.println("Before fighting BOSS...");originator.display();//存檔Caretaker caretaker = new Caretaker();caretaker.setMemento(originator.saveMemento());//FightingSystem.out.println("Fighting...");originator.setBloodValue(20);originator.setMagicValue(20);originator.display();//回復(fù)存檔System.out.println("Restore...");originator.restoreMemento(caretaker.getMemento());originator.display();輸出結(jié)果:
Before fighting BOSS... 用戶當(dāng)前狀態(tài): 血量:100;藍(lán)量:100 Fighting... 用戶當(dāng)前狀態(tài): 血量:20;藍(lán)量:20 Restore... 用戶當(dāng)前狀態(tài): 血量:100;藍(lán)量:100在備忘錄模式中,最重要的就是備忘錄Memento了。備忘錄中存儲(chǔ)的就是原發(fā)器的部分或者所有的狀態(tài)信息,而這些狀態(tài)信息是不能夠被其它對(duì)象所訪問(wèn)的,也就是說(shuō)我們是不可能在備忘錄之外的對(duì)象來(lái)存儲(chǔ)這些狀態(tài)信息,如果暴漏了內(nèi)部狀態(tài)信息就違反了封裝的原則,故備忘錄是處理原發(fā)器外其它對(duì)象都是不可以訪問(wèn)的。
優(yōu)缺點(diǎn)
優(yōu)點(diǎn):
缺點(diǎn):
適用場(chǎng)景
JDK中的備忘錄模式:
java.util.Date(Date對(duì)象通過(guò)自身內(nèi)部的一個(gè)long值來(lái)實(shí)現(xiàn)備忘錄模式)
java.io.Serializable
參考資料
歡迎跳轉(zhuǎn)到本文的原文鏈接:https://honeypps.com/design_pattern/memento/
歡迎支持筆者新作:《深入理解Kafka:核心設(shè)計(jì)與實(shí)踐原理》和《RabbitMQ實(shí)戰(zhàn)指南》,同時(shí)歡迎關(guān)注筆者的微信公眾號(hào):朱小廝的博客。
總結(jié)
以上是生活随笔為你收集整理的设计模式:备忘录模式(Memento)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Sping+ActiveMQ整合
- 下一篇: 设计模式:观察者模式(Observer)