Chinaunix首页 | 论坛 | 博客
  • 博客访问: 164478
  • 博文数量: 60
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 638
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-26 10:59
个人简介

喜欢coding,因为那是一件伟大的事情,是将无生命的IC赋予灵魂的过程,让我拥有了和上帝一样的成就感。(w1c2g3@163.com)

文章分类

全部博文(60)

文章存档

2017年(7)

2016年(41)

2015年(1)

2014年(4)

2013年(7)

我的朋友

分类: C/C++

2016-10-30 23:17:01

备忘录模式 当你需要让对象返回之前的状态时(例如,你的用户请求“撤销”),就使用备忘录模式(MementoPattern)




  1. #include <iostream>

  2. using namespace std;


  3. struct GameMemento {
  4. public:
  5.     GameMemento() : state("") {}
  6.     GameMemento(string state) {
  7.         this->state = state;
  8.     }
  9.     string getState() {
  10.         return state;
  11.     }
  12.     void setState(string state) {
  13.         this->state = state;
  14.     }
  15. private:
  16.     string state;
  17. };

  18. struct MasterGameObject {
  19. public:
  20.     MasterGameObject() : state("") {}
  21.     string getState(void) {
  22.         return state;
  23.     }
  24.     void setState(string state) {
  25.         this->state = state;
  26.     }
  27.     GameMemento *createGameMemento() {
  28.         return new GameMemento(state);
  29.     }
  30.     void restoreMemento(GameMemento *gameMemento) {
  31.         this->setState(gameMemento->getState());
  32.     }

  33. private:
  34.     string state;
  35. };

  36. struct Caretaker {
  37. public:
  38.     GameMemento *getGameMemento() {
  39.         return &gameMemento;
  40.     }
  41.     void setGameMemento(GameMemento *gameMemento) {
  42.         this->gameMemento = *gameMemento;
  43.     }
  44. private:
  45.     GameMemento gameMemento;
  46. };


  47. int main(int argc, char **argv) {
  48.     MasterGameObject *game = new MasterGameObject();
  49.     game->setState("state 1");
  50.     cout << "Initial state: " << game->getState() << endl;

  51.     Caretaker *caretaker = new Caretaker();
  52.     caretaker->setGameMemento(game->createGameMemento());

  53.     game->setState("state 2");
  54.     cout << "Changed state: " << game->getState() << endl;

  55.     game->restoreMemento(caretaker->getGameMemento());
  56.     cout << "Restored state: " << game->getState() << endl;
  57. }

阅读(944) | 评论(0) | 转发(0) |
0

上一篇:解释器模式

下一篇:原型模式

给主人留下些什么吧!~~