zoukankan      html  css  js  c++  java
  • 存档模式 Memento

    定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样就可以将该对象恢复到原先保存的状态

    类型:行为类

    类图:

    class Memento{
    public:
        Memento(int level,int life,int time):m_level(level),m_life(life),m_time(time){}
        Memento * GetState(){
            return this;
        }
        int GetLevel(){
            return m_level;
        }
        int Getlife(){
            return m_life;
        }
        int Gettime(){
            return m_time;
        }
    private:
        int m_level;
        int m_life;
        int m_time;
    };
    
    class Role{
    public:
        Role(int level,int life,int time):m_level(level),m_life(life),m_time(time){}
        void LoadMem(Memento * pmem){
            m_level = pmem->GetLevel();
            m_life = pmem->Getlife();
            m_time = pmem->Gettime();
        }
    
        Memento * CreateMem(){
            return new Memento(m_level,m_life,m_time);
        }
    
        void Upgrade(){
            this->m_level += 1 ;
            this->m_life += 10;
            this->m_time += 10;
        }
        void show(){
            cout<<"~~~~~~~~state~~~~~~~~~~"<<endl;
            cout<<"level : "<<m_level<<endl;
            cout<<"life : "<<m_life<<endl;
            cout<<"time : "<<m_time<<endl;
        }
    private:
        int m_level;
        int m_life;
        int m_time;
    };
    
    class ManagerMem{
    public:
        void AddMem(Memento * p){
            memvec.push_back(p);
        }
        Memento * GetMem(int index){
            return memvec[index];
        }
        ~ManagerMem(){
            vector<Memento *>::iterator it = memvec.begin();
            for(; it != memvec.end();it++)
                delete *it;
        }
    private:
        vector<Memento *>  memvec;
    };
    
    int main(int argc,char * argv[]){
        ManagerMem * pmanager = new ManagerMem;
        Role * prole = new Role(1,20,30);
        prole->show();
    
        prole->Upgrade();
        prole->show();
        
        cout<<"存档管理器添加存档:"<<endl;
        pmanager->AddMem(prole->CreateMem());
    
        prole->Upgrade(); prole->show();
        prole->Upgrade(); prole->show();
        //断电了,升级失败,只能恢复原来的存档
        
        cout<<"加载存档:"<<endl;
        prole->LoadMem(pmanager->GetMem(0));
        prole->show();
    
        delete prole;
        delete pmanager;
    }
  • 相关阅读:
    shell 命令参数
    Windows系统配置Python环境,python2和python3共存
    jmeter面试题及答案
    接口测试
    python语法基础
    pycharm环境安装及注册
    Win10下python 2.7与python 3.6双环境安装图文教程
    eclipse中导入maven项目时pom文件报错
    ssm-crud项目--总结
    ssm-crud项目——分页查询
  • 原文地址:https://www.cnblogs.com/xiumukediao/p/4657261.html
Copyright © 2011-2022 走看看