zoukankan      html  css  js  c++  java
  • 设计模式:memento模式

    目的:在不破坏系统封装性的前提下,记录系统每一步的状态,可以做到状态回退和前进

    方法:

    • 定义一个数据类,保存所有相关数据
    • 定义一个管理类,提供保存和恢复的接口
    • 具体操作类调用管理类的保存和恢复接口

    例子:

    class Memento   //状态数据类
    {
    	int money;
    public:
    	Memento(int money)
    	{
    		this->money = money;
    	}
    	
    	void setMoney(int money)
    	{
    		this->money = money;
    	}
    	
    	int getMoney()
    	{
    		return money;
    	}
    };
    
    class MakeMoney
    {
    	int money;
    	vector<Memento*> v;
    public:
    	MakeMoney(int money)
    	{
    		this->money = money;
    	}
    	
    	void storeMemento() //保存状态
    	{
    		Memento* m = new Memento(money);
    		v.push_back(m);
    	}
    	
    	void restoreMemento() //回退状态
    	{
    		if(v.size() != 0)
    		{
    			Memento* m = v.back();
    			v.pop_back();
    			this->money = m->getMoney();
    			delete m;
    		}
    	}
    	
    	void go()
    	{
    		storeMemento();
    		//srand(); //每次设置不同的种子即可
    		int rand = random() % 11;   //1 - 10的随机数
    		money = rand;
    	}
    	
    	void print()
    	{
    		cout << "money = " << money << endl;
    	}
    };
    
    int main() 
    {
    	MakeMoney* mm = new MakeMoney(1);
    	mm->go();
    	mm->print();
    	
    	mm->go();
    	mm->print();
    	
    	mm->restoreMemento();
    	mm->print();
    	
    	mm->restoreMemento();
    	mm->print();
    	
    	return 0;
    }
    
  • 相关阅读:
    五彩珠游戏
    repeater 的编辑功能
    客户端禁止cokice后,对session的影响.
    IIS无法运行ASP程序?
    winXP 密码 破解 重置
    winXP 密码 破解 重置
    IIS无法运行ASP程序?
    winXP 密码 破解 重置
    winXP 密码 破解 重置
    1.大批量数据操作
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11434143.html
Copyright © 2011-2022 走看看