备忘录模式

作者: 张霸天 | 来源:发表于2017-03-31 13:18 被阅读0次
    
    
    #include <stdio.h>
    #include <iostream>
    using namespace std;
    
    class RoleStateMemento;
    
    class GameRole {
    private :
        int vit;
        int attack;
        int def;
        
    public:
        void setVitality(int vitality){vit = vitality;}
        void setDefence(int defence){def = defence;}
        void setAttack(int attack) {this->attack = attack;}
        
        int getVitality(){return vit;}
        int getDefence(){return def;}
        int getAttack(){return attack;}
        
        void StateDisplay(){
            cout<<"current state:"<<endl;
            cout<<"vitality"<<vit<<endl;
            cout<<"attack"<<attack<<endl;
            cout<<"defence"<<def<<endl;
        }
        
        RoleStateMemento * SaveState();
        void RecoveryState(RoleStateMemento * memento);
        
        void GetInitState(){
            vit = 100;
            attack = 100;
            def = 100;
        }
        void Fight(){
            vit = 0;
            attack = 0;
            def = 0;
    
        }
    };
    
    class RoleStateMemento {
        
    private :
        int vit;
        int attack;
        int def;
        
    public:
        RoleStateMemento(int vit,int attack ,int def):vit(vit),attack(attack),def(def){}
        int getVitality(){return vit;}
        int getDefence(){return def;}
        int getAttack(){return attack;}
    };
    
    class RoleStateCaretaker {
    private:
        RoleStateMemento * memento;
    public:
        void setMemento (RoleStateMemento * memento){this->memento = memento;}
        RoleStateMemento * getMemento(){return memento;}
    };
    
    //.m
    
    RoleStateMemento * GameRole::SaveState() {
        return new RoleStateMemento(vit,attack,def);
    }
    
    void GameRole::RecoveryState(RoleStateMemento *memento) {
        this->vit = memento->getVitality();
        this->attack = memento->getAttack();
        this->def = memento->getDefence();
    }
    
    
    
    
    void testLesson14(){
        GameRole * lixiaoyao = new GameRole();
        lixiaoyao->GetInitState();
        lixiaoyao->StateDisplay();
        
        RoleStateCaretaker * stateAdmin = new RoleStateCaretaker();
        stateAdmin->setMemento(lixiaoyao->SaveState());
        
        lixiaoyao->Fight();
        lixiaoyao->StateDisplay();
        
        lixiaoyao->RecoveryState(stateAdmin->getMemento());
        lixiaoyao->StateDisplay();
        
    
    }
    
    

    备忘录模式: 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这种状态,这样以后就可将该对象恢复到原先保存的状态。
    缺点:角色状态需要完整存贮到备忘录对象中,如果数据很大很多,就会在资源的消耗上比较大。

    相关文章

      网友评论

        本文标题:备忘录模式

        本文链接:https://www.haomeiwen.com/subject/zbpeottx.html