W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
你想預(yù)測對一個對象做出改變后的反應(yīng)。
使用備忘錄模式(Memento Pattern)來跟蹤一個對象的變化。使用這個模式的類會輸出一個存儲在其他地方的備忘錄對象。
如果你的應(yīng)用程序可以讓用戶編輯文本文件,例如,他們可能想要撤銷上一個動作。你可以在用戶改變文件之前保存文件現(xiàn)有的狀態(tài),然后回滾到上一個位置。
class PreserveableText
class Memento
constructor: (@text) ->
constructor: (@text) ->
save: (newText) ->
memento = new Memento @text
@text = newText
memento
restore: (memento) ->
@text = memento.text
pt = new PreserveableText "The original string"
pt.text # => "The original string"
memento = pt.save "A new string"
pt.text # => "A new string"
pt.save "Yet another string"
pt.text # => "Yet another string"
pt.restore memento
pt.text # => "The original string"
備忘錄對象由PreserveableText#save返回,為了安全保護,分別地存儲著重要的狀態(tài)信息。你可以序列化備忘錄以便來保證硬盤中的“撤銷”緩沖或者是那些被編輯的圖片等數(shù)據(jù)密集型對象。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: