Design Patterns 18: Memento
阿新 • • 發佈:2018-12-15
在不違反封裝原則的前提下,捕獲記錄物件的內部狀態,使得物件具備復原的能力。
struct Memento { int GetState() { return _state; }; void SetState(Memento* m) { _state = m->GetState(); }; Memento(int state) : _state(state) {} private: int _state; }; struct Originator { void SetMemento(Memento* m) { _state = m->GetState(); } Memento* CreateMemento() { return new Memento(_state); } Originator(int state) : _state(state) {} private: int _state; }; int main() { Originator originator(10); auto memento = originator.CreateMemento(); originator.SetMemento(memento); }