MementoPattern.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class Memento {
  5. private:
  6. friend class Originator;
  7. Memento(const string& st) {
  8. _st = st;
  9. }
  10. void SetState(const string& st) {
  11. _st = st;
  12. }
  13. string GetState() {
  14. return _st;
  15. }
  16. private:
  17. string _st;
  18. };
  19. class Originator {
  20. public:
  21. Originator() {
  22. _mt = nullptr;
  23. }
  24. Originator(const string &st) {
  25. _st = st;
  26. _mt = nullptr;
  27. }
  28. Memento* CreateMemento() {
  29. return new Memento(_st);
  30. }
  31. void SetMemento(Memento* mt) {
  32. _mt = mt;
  33. }
  34. void RestoreToMemento(Memento* mt) {
  35. _st = mt->GetState();
  36. }
  37. string GetState() {
  38. return _st;
  39. }
  40. void SetState(const string& st) {
  41. _st = st;
  42. }
  43. void PrintState() {
  44. cout << _st << "..." << endl;
  45. }
  46. private:
  47. string _st;
  48. Memento *_mt;
  49. };
  50. int main() {
  51. Originator *o = new Originator();
  52. o->SetState("old");
  53. o->PrintState();
  54. Memento *m = o->CreateMemento();
  55. o->SetState("new");
  56. o->PrintState();
  57. o->RestoreToMemento(m);
  58. o->PrintState();
  59. delete o;
  60. delete m;
  61. return 0;
  62. }