备忘录模式和策略模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了备忘录模式和策略模式相关的知识,希望对你有一定的参考价值。
1、备忘录模式
保存对象的状态,在需要的时候在恢复出来即可!!!
2、具体实现
(1)、代码实现
#include<iostream> #include<string> using namespace std; class Mem{ //备忘录类 public: Mem(string name, int age){ m_name = name; m_age = age; } string getName(){ return m_name; } int getAge(){ return m_age; } void setName(string name){ m_name = name; } void setAge(int age){ m_age = age; } private: string m_name; int m_age; }; class Person{ public: Person(string name, int age){ m_name = name; m_age = age; } string getName(){ return m_name; } int getAge(){ return m_age; } void setName(string name){ m_name = name; } void setAge(int age){ m_age = age; } //保存 Mem *createMem(){ return new Mem(m_name, m_age); } //还原 void setMem(Mem *mem){ this->m_age = mem->getAge(); this->m_name = mem->getName(); } void printT(){ cout<<"m_name: "<<m_name<<"m_age: "<<m_age<<endl; } private: string m_name; int m_age; }; //增加一个备忘录的管理者!!! class Manager{ public: Manager(Mem *m){ this->m = m; } Mem *getMem(){ return m; } void setMem(Mem *m){ this->m = m; } private: Mem *m; //持有一个备忘录的引用!!! }; int main(void){ /* Mem *m = NULL; Person *p = new Person("张三",32); p->printT(); //创建Person对象的一个状态 cout<<"---------------------------"<<endl; m = p->createMem(); p->setAge(42); p->printT(); cout<<"还原旧的状态"<<endl; p->setMem(m); p->printT(); delete p; */ Manager *m1; Person *p = new Person("张三",32); p->printT(); //创建Person对象的一个状态 cout<<"---------------------------"<<endl; m1 = new Manager(p->createMem()); p->setAge(42); p->printT(); cout<<"还原旧的状态"<<endl; p->setMem(m1->getMem()); p->printT(); delete p; return 0; }
(2)、结果如下
3、策略模式
准备一组算法,并将每一个算法封装起来,使得它们可以互换;
4、具体实现
(1)、代码如下
#include<iostream> using namespace std; //策略模式:准备一组算法,并将每一个算法封装起来,使得它们可以互换; class Strategy{ public: virtual void crypt() = 0; private: }; class AES : public Strategy{ public: virtual void crypt(){ cout<<"AES加密算法"<<endl; } private: }; class DES : public Strategy{ public: virtual void crypt(){ cout<<"DES加密算法"<<endl; } private: }; class Context{ //组合算法的抽象类 public: void setStrategy(Strategy *strategy){ this->strategy = strategy; } void myoperator(){ strategy->crypt(); } private: Strategy *strategy; }; int main(void){ //1、直接调用的方法; /* DES *des = new DES; des->crypt(); delete des; */ //2、客户端可以自由的进行策略的更换; //Strategy *des = new DES; Strategy *des = new AES; Context *context = new Context; context->setStrategy(des); context->myoperator(); delete des; delete context; return 0; }
(2)、运行结果
本文出自 “wait0804” 博客,请务必保留此出处http://wait0804.blog.51cto.com/11586096/1885898
以上是关于备忘录模式和策略模式的主要内容,如果未能解决你的问题,请参考以下文章