无论是我们在使用word还是记事本,系统都会为我们提供撤销的功能,这几乎是人人都会使用到的功能,而在我们实际开发中,会不会存在一个很复杂的对象,当更改了其中的某一个属性以后,也提供撤销的功能,可以快速恢复到更新前的状态。提供该功能的模式也正是今天的主题——备忘录模式。
一、概念理解
书中的备忘录解释说,在不破坏封装的情况下,捕获对象的内部状态并将该状态保存在对象外部,以便稍后可以将该对象恢复到其先前保存的状态。
[En]
The memo in the book explains that, without breaking the encapsulation, capture the internal state of an object and save that state outside the object, so that the object can be restored to its previously saved state later.
实际上,它是向一个对象添加一个额外的复制对象。每次我们更改对象的某些属性时,我们都会构建一个副本并将该副本存储在队列中。每当回滚对象时,都会从副本中恢复数据。
[En]
In fact, it is to add an additional copy object to an object. Every time we change some properties on the object, we build a copy and store the copy in a queue. Whenever the object is rolled back, the data is restored from the copy.
很显然需要三个角色:原对象、副本对象、存放副本的队列。
也即书上的三个角色定义:
Originator(发起人角色):负责创建一个备忘录,记录自身需要保存的状态,具备状态回滚功能;即原对象。
Memento(备忘录角色):用于存储Originator的内部状态,且可以防止Originator以外的对象进行访问;即副本对象。
Caretaker(管理员角色):负责存储、提供管理Memento,无法对Memento的内容进行操作和访问;也即存放副本的队列。
为了将这个概念落到实处,我们基于备忘录模式的思想实现了视频草稿箱的功能。
[En]
In order to put the concept on the ground, we realize the function of video draft box based on the idea of memo mode.