作用:
封裝的對象可以在對象觸發行為時進行狀態的記錄與保存
也可以進行狀態的回退,恢復之前的狀態
示例:
class Editor{constructor(){this.allText = ''}edit(text){this.allText += text}saveNow(){return new EditorText(this.allText)}backspacing(editorText){this.allText = editorText.getText()console.log(this.allText,'???')}}class EditorText{constructor(text){this.text = text}getText(){return this.text}}class History{constructor(){this.textNodeList = []}add(text){this.textNodeList.push(text)}delete(){this.textNodeList.pop()return this.textNodeList[this.textNodeList.length-1]}}const editor = new Editor()const history = new History()editor.edit('兩個黃鸝鳴翠柳,')history.add(editor.saveNow())console.log(editor,'當前文本1')console.log(history,'歷史記錄1')editor.edit('一行白鷺上西天。')history.add(editor.saveNow())console.log(editor,'當前文本2')console.log(history,'歷史記錄2')//寫的不對,撤回一下editor.backspacing(history.delete())console.log(editor,'當前文本3')console.log(history,'歷史記錄3')editor.edit('一行白鷺上青天。')history.add(editor.saveNow())console.log(editor,'當前文本4')console.log(history,'歷史記錄4')