目的
在不違反封裝性的前提下,捕捉物件的內部狀態並存在外面,以便日後回復至此一狀態。
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.
適用
- 當物件的部分狀態必須先存起來(快照),以備事後能回復至此一狀態時。
- 直接取得狀態的介面會暴露內部實作細節,因而違反物件封裝性時。
結構及成員
Collaborations: Caretaker向Originator索取一個Memento物件,持有一陣子之後再送回給Originator。
影響結果
好處
壞處
實作
儲存異動之處
如果Memento的建立及傳遞流程完全合乎預期的話,那麼Memento就可以只儲存與Originator的內部狀態有異動之處(Incremental Change)。
Example: Memento
Class: Originator
package memento;
class Originator {
private String state;
public void set(String state) {
System.out.println("Originator: Setting state to " + state);
this.state = state;
}
public Memento saveToMemento() {
System.out.println("Originator: Saving to Memento.");
return new Memento(state);
}
public void restoreFromMemento(Memento m) {
state = m.getSavedState();
System.out.println("Originator: State after restoring from Memento: " + state);
}
}
Class: Memento
package memento;
import java.util.*;
class Memento {
private String state;
public Memento(String stateToSave) {
state = stateToSave;
}
public String getSavedState() {
return state;
}
}
Class: CareTaker
package memento;
import java.util.ArrayList;
class Caretaker {
private ArrayList<Memento> savedStates = new ArrayList<Memento>();
public void addMemento(Memento m) {
savedStates.add(m);
}
public Memento getMemento(int index) {
return savedStates.get(index);
}
}
Class: MementoExample
package memento2;
class MementoExample {
public static void main(String[] args) {
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
originator.set("State1");
originator.set("State2");
caretaker.addMemento(originator.saveToMemento());
originator.set("State3");
caretaker.addMemento(originator.saveToMemento());
originator.set("State4");
originator.restoreFromMemento(caretaker.getMemento(1));
}
}
Result:
Originator: Setting state to State1
Originator: Setting state to State2
Originator: Saving to Memento.
Originator: Setting state to State3
Originator: Saving to Memento.
Originator: Setting state to State4
Originator: State after restoring from Memento: State3