您好,登錄后才能下訂單哦!
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)、運行結果
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。