设计模式之备忘录模式

1.简介

// 备忘录设计模式.cpp : 定义控制台应用程序的入口点。

//备忘录设计模式简述:备忘录对象是一个对象用来存储另一个对象的快照的对象,用意是在不破坏封装条件下
//将一个对象的状态记录下,并外部化存储起来,从而在合适的时候把对象还原到存储起来的状态

//备忘录设计模式三大步骤
//1.设计记录的节点,存储记录
//2.设计记录的存储,vector,list,map,set,链表,图,数组,树
//3.操作记录的类,记录节点状态,设置节点状态,显示状态

//什么时候要备忘录模式:1.设计需要回放的软件,2.记录事物的状态,3.数据库备份,4.文档的编辑,撤销操作

2.代码

class weather//记录节点
{
public:
    string state;
    weather(string state)//记录当前天气状态
    {
        this->state = state;
    }
};
class allweath//记录的存储
{
public:
    vector<weather*> records;
    void save(weather *we)
    {
        records.push_back(we);
    }

    weather *get(int i)
    {
        return records[i];
    }
};

class opweather//操作记录的类
{
public:
    string state;
    void setweather(weather *we)
    {
        this->state = we->state;
    }
    weather *createweather()
    {
        return new weather(this->state);
    }
    void show()
    {
        cout << state << endl;
    }

};


int _tmain(int argc, _TCHAR* argv[])
{
    allweath *aw = new allweath;
    opweather *ow = new opweather;
    ow->state = "阴天";
    ow->show();
    aw->save(ow->createweather());

    ow->state = "多云";
    ow->show();
    aw->save(ow->createweather());

    ow->state = "晴天";
    ow->show();
    aw->save(ow->createweather());

    ow->state = "小雨";
    ow->show();
    aw->save(ow->createweather());

    ow->setweather(aw->get(3));
    ow->show();
    cin.get();
}

3.运行结果

原文地址:https://www.cnblogs.com/huipengbo/p/8094033.html