备忘录模式

Originator(原生者)
需要被保存状态以便恢复的那个对象。
Memento(备忘录)
该对象由Originator创建,用来保存Originator的内部状态
Caretaker(管理者)
负责在适当的时间保存/恢复Originator对象的状态
适用于:
在不破坏疯转的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样就可以将以后的对象状态恢复到之前保存的状态。
适用于功能比较复杂的,但是需要记录或者维护属性历史的类;或者需要保存的属性只是众多属性中的一小部分时Originator可以根据保存的Memento还原到前一个状态。
结构图:
这里写图片描述

需求:
现有一个男孩,没有追妹子前元气满满,但是和妹子表白后,很难受,通过备忘录恢复后又变的元气满满。

class Originator;
class Memento{
private:
    string state;
    friend class Originator;
    Memento(string state){
        this->state = state;
    }
};
class Originator{
private:
    string state;
public:
    void setState(string state){
        this->state = state;
    }
    Memento* creatMemento(){
        return new Memento(state);
    }
    void reStoreMemento(Memento *memo){
        state = memo->state;
    }
    void show(){
        cout << "当前状态:" << state << endl;
    }
};

class CareTaker{
private:
    vector<Memento*> vec;
public:
    void setMemento(Memento *m){
        vec.push_back(m);
    }
    Memento* getMemento(int index){
        vector<Memento*>::iterator it;
        it = vec.begin();//集合下标从1开始
        it += index - 1;
        return *it;
    }
};

客户端:

int main(void){
    Originator *po = new Originator();
    po->setState("没有追妹子前元气满满");
    po->show();
    CareTaker *pc = new CareTaker();
    pc->setMemento(po->creatMemento());
    po->setState("表白被拒难受的一批");
    po->show();
    pc->setMemento(po->creatMemento());
    po->reStoreMemento(pc->getMemento(1));
    po->show();
    system("pause");
    return 0;
}

调试效果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值