Design Pattern --- Memento
class Originator; class Memento { // data. int m_x, m_y; friend class Originator; private: Memento(int x, int y) : m_x(x), m_y(y) {} }; class Originator { // data. int m_x, m_y; public: Originator(int x, int y) : m_x(x), m_y(y) {} public: // Interface. void Move(int x, int y) { cout <<"move to: " <<(m_x = x) <<", " <<(m_y = y) <<endl; } Memento GetMemento() const { return Memento(m_x, m_y); } void SetMemento(Memento m) { m_x = m.m_x; m_y = m.m_y; cout <<"current position is: " <<m_x <<", " <<m_y <<endl; } }; int main() { Originator o(0, 0); Memento m1 = o.GetMemento(); o.Move(1, -4); Memento m2 = o.GetMemento(); o.SetMemento(m1); // Back to 'm1'. o.SetMemento(m2); // Back to 'm2'. return 0; }
Memento 模式本质就是将某个复杂对象的当前状态单独封装为一个集合, 以便保存这个对象的状态.
还是那句话, 把易变的东西包装到类的外面.