设计模式的汇总演练

本文详细介绍了备忘录模式和策略模式的概念及其应用场景,包括如何通过备忘录模式实现对象状态的备份与恢复,以及策略模式如何帮助实现算法的灵活替换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.youkuaiyun.com/waldmer/article/details/50477616

备忘录模式

数据库的备份,文档编辑中的撤销等功能

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <vector>  
  4. using namespace std;  
  5.   
  6. //备忘录模式:备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。  
  7. //备忘录模式的用意是在不破坏封装的条件下,将一个对象的状态捉住,  
  8. //并外部化,存储起来,从而可以在将来合适的时候把这个对象还原到存储起来的状态。  
  9. //同时跟几个MM聊天时,一定要记清楚刚才跟MM说了些什么话  
  10. //,不然MM发现了会不高兴的哦,幸亏我有个备忘录,  
  11. //刚才与哪个MM说了什么话我都拷贝一份放到备忘录里面保存,  
  12. //这样可以随时察看以前的记录啦  
  13. //设计需要回放的软件,记录一下事物的状态。数据库备份,文档的编译,撤销,恢复  
  14. //设计备忘录三大步骤  
  15. //1.设计记录的节点,存储记录,//记录鼠标,键盘的状态  
  16. //2.设计记录的存储,vector,list,map,set,链表,图,数组,树  
  17. //3.操作记录的类,记录节点状态,设置节点状态,显示状态,0.1秒记录一下  
  18.   
  19. //备忘录的节点,  
  20. class Memo  
  21. {  
  22. public:  
  23.     string state;  
  24.     Memo(string state) //记录当前的状态,  
  25.     {  
  26.         this->state = state;  
  27.     }  
  28. };  
  29.   
  30. class Originator//类的包含备忘录的节点  
  31. {  
  32. public:  
  33.     string state;  
  34.     void setMemo(Memo *memo)  
  35.     {  
  36.         state = memo->state;  
  37.     }  
  38.     Memo *createMemo()  
  39.     {  
  40.         return new Memo(state);  
  41.     }  
  42.     void show()  
  43.     {  
  44.         cout << state << endl;  
  45.     }  
  46. };  
  47.   
  48.   
  49. //备忘录的集合  
  50. class Caretaker  
  51. {  
  52. public:  
  53.     vector<Memo *> memo;  
  54.     void save(Memo *memo)  
  55.     {  
  56.         (this->memo).push_back(memo);  
  57.     }  
  58.     Memo *getState(int i)  
  59.     {  
  60.         return memo[i];  
  61.     }  
  62. };  
  63.   
  64. int main1()  
  65. {  
  66.     Originator *og = new Originator();  
  67.     Caretaker *ct = new Caretaker();  
  68.   
  69.     og->state = "on";  
  70.     og->show();  
  71.     ct->save(og->createMemo());  
  72.   
  73.     og->state = "off";  
  74.     og->show();  
  75.     ct->save(og->createMemo());  
  76.   
  77.     og->state = "middle";  
  78.     og->show();  
  79.     ct->save(og->createMemo());  
  80.   
  81.     og->setMemo(ct->getState(1));  
  82.     og->show();  
  83.   
  84.     og->setMemo(ct->getState(2));  
  85.     og->show();  
  86.     cin.get();  
  87.     return 0;  
  88. }  

策略模式

依赖于多态。

360服务端更新杀毒脚本进行客户端杀毒的操作。逻辑脚本存储在服务器,接口在客户端进行实现。

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <cmath>  
  3. #include <string>  
  4. using namespace std;  
  5.   
  6. //策略模式:策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,  
  7. //从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下  
  8. //发生变化。策略模把行为和环境分开。环境类负责维持和查询行为类,  
  9. //各种算法在具体的策略类中提供。由于算法和环境独立开来,算法的增减,  
  10. //修改都不会影响到环境和客户端。  
  11.   
  12. //跟不同类型的MM约会,要用不同的策略,有的请电影比较好,  
  13. //有的则去吃小吃效果不错,有的去海边浪漫最合适,单目的都是为了得到MM的芳心,  
  14. //我的追MM锦囊中有好多Strategy哦。  
  15. //策略的抽象类,接口,抽象类的指针可以访问所有子类对象,(纯虚函数)  
  16. //实现的各种策略,各种策略的实现类,都必须继承抽象类  
  17. //策略的设置接口类,设置不同策略  
  18.   
  19. class CashSuper  
  20. {  
  21. public:  
  22.     virtual double acceptMoney(double money) = 0;//抽象类,收钱的纯虚函数  
  23. };  
  24.   
  25. class CashNormal :public CashSuper  
  26. {  
  27. public:  
  28.     double acceptMoney(double money)//正常收钱  
  29.     {  
  30.         return money;  
  31.     }  
  32. };  
  33.   
  34. class CashRebate :public CashSuper //打折  
  35. {  
  36. private:  
  37.     double discount;  
  38. public:  
  39.     CashRebate(double dis) //折扣  
  40.     {  
  41.         discount = dis;  
  42.     }  
  43.     double acceptMoney(double money)//收钱  
  44.     {  
  45.         return money*discount;//折扣  
  46.     }  
  47. };  
  48.   
  49. class CashReturn :public CashSuper  
  50. {  
  51. private:  
  52.     double moneyCondition;  
  53.     double moneyReturn;  
  54. public:  
  55.     CashReturn(double mc, double mr)//花多少钱,返回多少钱  
  56.     {  
  57.         moneyCondition = mc;  
  58.         moneyReturn = mr;  
  59.     }  
  60.     double acceptMoney(double money)//收钱,返款  
  61.     {  
  62.         double result = money;  
  63.         if (money >= moneyCondition)  
  64.         {  
  65.             result = money - floor(money / moneyCondition)*moneyReturn;  
  66.         }  
  67.         return result;  
  68.     }  
  69. };  
  70.   
  71. class  CashContext  
  72. {  
  73. private:  
  74.     CashSuper *cs;  
  75. public:  
  76.     CashContext(string str)//设置策略  
  77.     {  
  78.         if (str == "正常收费")  
  79.         {  
  80.             cs = new CashNormal();  
  81.         }  
  82.         else if (str == "打9折")  
  83.         {  
  84.             cs = new CashRebate(0.9);  
  85.         }  
  86.         else if (str == "满1000送200")  
  87.         {  
  88.             cs = new CashReturn(1000200);  
  89.         }  
  90.     }  
  91.     double getResult(double money)  
  92.     {  
  93.         return cs->acceptMoney(money);  
  94.     }  
  95. };  
  96.   
  97. int main123 ()  
  98. {  
  99.     double money = 1000;  
  100.     CashContext *cc = new CashContext("正常收费");  
  101.     cout << cc->getResult(money);  
  102.     cin.get();  
  103.     return 0;  
  104. }  

抽象工厂

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. //工厂模式:客户类和工厂类分开。  
  6. //消费者任何时候需要某种产品,只需向工厂请求即可。  
  7.   
  8. //消费者无须修改就可以接纳新产品。缺点是当产品修改时,  
  9.   
  10. //工厂类也要做相应的修改。如:如何创建及如何向客户端提供。  
  11. //  
  12. //追MM少不了请吃饭了,麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西,  
  13. //虽然口味有所不同,但不管你带MM去麦当劳或肯德基,  
  14. //只管向服务员说“来四个鸡翅”就行了。麦当劳和肯德基就是生产鸡翅的Factory。  
  15.   
  16.   
  17. //消费者不固定,工厂者不固定,(工厂根据消费者的行为进行动作)  
  18.   
  19. //实现消费者抽象基类,消费者派生类的实现,实例化就是消费者  
  20.   
  21. //操作的抽象基类,实现派生类各种操作,实例化的操作  
  22. //工厂的抽象类,抽象类包含了两个抽象类的接口(消费者,操作)  
  23. //抽象类实现了工厂类的抽象,实例化的派生类,实现工厂,  
  24. //根据用户设置用户,根据操作设置操作  
  25.   
  26. class IUser  
  27. {  
  28. public:  
  29.     virtual void getUser() = 0;  //纯虚接口类,抽象类  
  30.     virtual void setUser() = 0;  
  31. };  
  32.   
  33. class SqlUser :public IUser   //继承抽象实现sql数据库使用者的实例化  
  34. {  
  35. public:  
  36.     void getUser()  
  37.     {  
  38.         cout << "在sql中返回user" << endl;  
  39.     }  
  40.     void setUser()  
  41.     {  
  42.         cout << "在sql中设置user" << endl;  
  43.     }  
  44. };  
  45.   
  46. class AccessUser :public IUser //继承抽象实现access数据库使用者的实例化  
  47. {  
  48. public:  
  49.     void getUser()  
  50.     {  
  51.         cout << "在Access中返回user" << endl;  
  52.     }  
  53.     void setUser()  
  54.     {  
  55.         cout << "在Access中设置user" << endl;  
  56.     }  
  57. };  
  58.   
  59. class IDepartment  //抽象类,提供接口  
  60. {  
  61. public:  
  62.     virtual void getDepartment() = 0;  
  63.     virtual void setDepartment() = 0;  
  64. };  
  65.   
  66. class SqlDepartment :public IDepartment  //SQL操作的实现  
  67. {  
  68. public:  
  69.     void getDepartment()  
  70.     {  
  71.         cout << "在sql中返回Department" << endl;  
  72.     }  
  73.     void setDepartment()  
  74.     {  
  75.         cout << "在sql中设置Department" << endl;  
  76.     }  
  77. };  
  78.   
  79. class AccessDepartment :public IDepartment //access操作的实现  
  80. {  
  81. public:  
  82.     void getDepartment()  
  83.     {  
  84.         cout << "在Access中返回Department" << endl;  
  85.     }  
  86.     void setDepartment()  
  87.     {  
  88.         cout << "在Access中设置Department" << endl;  
  89.     }  
  90. };  
  91.   
  92. class IFactory     //抽象工厂  
  93. {  
  94. public:  
  95.     virtual IUser *createUser() = 0;  
  96.     virtual IDepartment *createDepartment() = 0;  
  97. };  
  98.   
  99. class SqlFactory :public IFactory  //抽象工厂一个实现  
  100. {  
  101. public:  
  102.     IUser *createUser()  
  103.     {  
  104.         return new SqlUser();  
  105.     }  
  106.     IDepartment *createDepartment()  
  107.     {  
  108.         return new SqlDepartment();  
  109.     }  
  110. };  
  111.   
  112. class AccessFactory :public IFactory // 抽象工厂一个实现  
  113. {  
  114. public:  
  115.     IUser *createUser()  
  116.     {  
  117.         return new AccessUser();  
  118.     }  
  119.     IDepartment *createDepartment()  
  120.     {  
  121.         return new AccessDepartment();  
  122.     }  
  123. };  
  124.   
  125. /*************************************************************/  
  126. //变相的实现了静态类  
  127. class DataAccess  
  128. {  
  129. private:  
  130.     static string db;  
  131.     //string db="access";  
  132. public:  
  133.     static IUser *createUser()  
  134.     {  
  135.         if (db == "access")  
  136.         {  
  137.             return new AccessUser();  
  138.         }  
  139.         else if (db == "sql")  
  140.         {  
  141.             return new SqlUser();  
  142.         }  
  143.     }  
  144.     static IDepartment *createDepartment()  
  145.     {  
  146.         if (db == "access")  
  147.         {  
  148.             return new AccessDepartment();  
  149.         }  
  150.         else if (db == "sql")  
  151.         {  
  152.             return new SqlDepartment();  
  153.         }  
  154.     }  
  155. };  
  156.   
  157. string DataAccess::db = "sql";  
  158. /*************************************************************/  
  159.   
  160.   
  161. int main()  
  162. {  
  163.     //IFactory *factory=new SqlFactory();  
  164.     IFactory *factory;//抽象工厂  
  165.     IUser *user;//抽象消费者  
  166.     IDepartment *department;//提供的操作  
  167.   
  168.     factory = new AccessFactory();//基类的指针指指向派生类的对象  
  169.     user = factory->createUser();//基类的指针指向派生类的对象  
  170.     department = factory->createDepartment();//基类的指针指向派生类的对象  
  171.   
  172.     user->getUser();  
  173.     user->setUser();//访问acesss接口  
  174.   
  175.     department->getDepartment();  
  176.     department->setDepartment();//接口  
  177.   
  178.     user = DataAccess::createUser();  
  179.     department = DataAccess::createDepartment();  
  180.   
  181.     user->getUser();  
  182.     user->setUser();  
  183.     department->getDepartment();  
  184.     department->setDepartment();  
  185.   
  186.     cin.get();  
  187.     return 0;  
  188. }  

工厂方法模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. //工厂方法模式:核心工厂类不再负责所有产品的创建,  
  6. //而是将具体创建的工作交给子类去做,成为一个抽象工厂角色  
  7. //,仅负责给出具体工厂类必须实现的接口,  
  8. //而不接触哪一个产品类应当被实例化这种细节。  
  9.   
  10. //请MM去麦当劳吃汉堡,不同的MM有不同的口味,  
  11. //要每个都记住是一件烦人的事情,我一般采用Factory Method模式,  
  12. //带着MM到服务员那儿,说“要一个汉堡”,具体要什么样的汉堡呢,  
  13. //让MM直接跟服务员说就行了。  
  14.   
  15. class Operation  
  16. {  
  17. public:  
  18.     double numberA, numberB;  
  19.     virtual double  getResult()//  
  20.     {  
  21.         return 0;  
  22.     }  
  23. };  
  24.   
  25. class addOperation :public Operation  
  26. {  
  27.     double getResult()  
  28.     {  
  29.         return numberA + numberB;  
  30.     }  
  31. };  
  32.   
  33. class subOperation :public Operation  
  34. {  
  35.     double getResult()  
  36.     {  
  37.         return numberA - numberB;  
  38.     }  
  39. };  
  40.   
  41. class mulOperation :public Operation  
  42. {  
  43.     double getResult()  
  44.     {  
  45.         return numberA*numberB;  
  46.     }  
  47. };  
  48.   
  49. class divOperation :public Operation  
  50. {  
  51.     double getResult()  
  52.     {  
  53.         return numberA / numberB;  
  54.     }  
  55. };  
  56.   
  57. class IFactory  
  58. {  
  59. public:  
  60.     virtual Operation *createOperation() = 0;  
  61. };  
  62.   
  63.   
  64. class AddFactory :public IFactory  
  65. {  
  66. public:  
  67.     static Operation *createOperation()  
  68.     {  
  69.         return new addOperation();  
  70.     }  
  71. };  
  72.   
  73. class SubFactory :public IFactory  
  74. {  
  75. public:  
  76.     static Operation *createOperation()  
  77.     {  
  78.         return new subOperation();  
  79.     }  
  80. };  
  81.   
  82. class MulFactory :public IFactory  
  83. {  
  84. public:  
  85.     static Operation *createOperation()  
  86.     {  
  87.         return new mulOperation();  
  88.     }  
  89. };  
  90.   
  91. class DivFactory :public IFactory  
  92. {  
  93. public:  
  94.     static Operation *createOperation()  
  95.     {  
  96.         return new divOperation();  
  97.     }  
  98. };  
  99.   
  100. int mainw()  
  101. {  
  102.     Operation *oper = MulFactory::createOperation();  
  103.     oper->numberA = 9;  
  104.     oper->numberB = 99;  
  105.     cout << oper->getResult() << endl;  
  106.     cin.get();  
  107.     return 0;  
  108. }  

简单工厂模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. //工厂模式:客户类和工厂类分开。  
  6. //消费者任何时候需要某种产品,只需向工厂请求即可。  
  7. //消费者无须修改就可以接纳新产品。缺点是当产品修改时,  
  8. //工厂类也要做相应的修改。如:如何创建及如何向客户端提供。  
  9. //  
  10. //追MM少不了请吃饭了,麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西,  
  11. //虽然口味有所不同,但不管你带MM去麦当劳或肯德基,  
  12. //只管向服务员说“来四个鸡翅”就行了。麦当劳和肯德基就是生产鸡翅的Factory。  
  13.   
  14.   
  15. //第一,基类存放数据  
  16. //第二,派生类有很多,派生类存放数据的操作  
  17. //第三实现接口类,用静态函数实现调用各种派生类  
  18.   
  19. class Operation    //基类存放数据  
  20. {  
  21. public:  
  22.     double numberA, numberB;//两个数  
  23.     virtual double  getResult()//获取结果  
  24.     {  
  25.         return 0;  
  26.     }  
  27. };  
  28.   
  29. class addOperation :public Operation//派生类存放操作  
  30. {  
  31.     double getResult()  
  32.     {  
  33.         return numberA + numberB;  
  34.     }  
  35. };  
  36.   
  37. class subOperation :public Operation  
  38. {  
  39.     double getResult()  
  40.     {  
  41.         return numberA - numberB;  
  42.     }  
  43. };  
  44.   
  45. class mulOperation :public Operation  
  46. {  
  47.     double getResult()  
  48.     {  
  49.         return numberA*numberB;  
  50.     }  
  51. };  
  52.   
  53. class divOperation :public Operation  
  54. {  
  55.     double getResult()  
  56.     {  
  57.         return numberA / numberB;  
  58.     }  
  59. };  
  60.   
  61. class operFactory //实现调用改革吃哦啊做  
  62. {  
  63. public:  
  64.     static Operation *createOperation(char c)  
  65.     {  
  66.         switch (c)  
  67.         {  
  68.         case '+':  
  69.             return new addOperation;  
  70.             break;  
  71.   
  72.         case '-':  
  73.             return new subOperation;  
  74.             break;  
  75.   
  76.         case '*':  
  77.             return new mulOperation;  
  78.             break;  
  79.   
  80.         case '/':  
  81.             return new divOperation;  
  82.             break;  
  83.         }  
  84.     }  
  85. };  
  86.   
  87. int mainV()  
  88. {  
  89.     Operation *oper = operFactory::createOperation('-');  
  90.     oper->numberA = 9;  
  91.     oper->numberB = 99;  
  92.     cout << oper->getResult() << endl;  
  93.   
  94.     cin.get();  
  95.     return 0;  
  96. }  

代理模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. //代理模式:代理模式给某一个对象提供一个代理对象,  
  5. //并由代理对象控制对源对象的引用。  
  6. //代理就是一个人或一个机构代表另一个人或者一个机构采取行动。  
  7. //某些情况下,客户不想或者不能够直接引用一个对象,  
  8. //代理对象可以在客户和目标对象直接起到中介的作用。  
  9. //客户端分辨不出代理主题对象与真实主题对象。  
  10. //代理模式可以并不知道真正的被代理对象,  
  11. //而仅仅持有一个被代理对象的接口,这时候代理对象不能够创建被代理对象,  
  12. //被代理对象必须有系统的其他角色代为创建并传入。  
  13. //跟MM在网上聊天,一开头总是“hi, 你好”,   
  14. //“你从哪儿来呀?”“你多大了?”“身高多少呀?”  
  15. //这些话,真烦人,写个程序做为我的Proxy吧,  
  16. //凡是接收到这些话都设置好了自己的回答,  
  17. //接收到其他的话时再通知我回答,怎么样,酷吧。  
  18.   
  19. class SchoolGirl  
  20. {  
  21. public:  
  22.     string name;  
  23. };  
  24.   
  25. class IGiveGift  
  26. {  
  27. public:  
  28.     virtual void giveDolls() = 0;  
  29.     virtual void giveFlowers() = 0;  
  30. };  
  31.   
  32. class Pursuit :public IGiveGift  
  33. {  
  34. private:  
  35.     SchoolGirl mm;  
  36. public:  
  37.     Pursuit(SchoolGirl m)  
  38.     {  
  39.         mm = m;  
  40.     }  
  41.     void giveDolls()  
  42.     {  
  43.         cout << mm.name << " 送你娃娃" << endl;  
  44.     }  
  45.     void giveFlowers()  
  46.     {  
  47.         cout << mm.name << " 送你鲜花" << endl;  
  48.     }  
  49. };  
  50.   
  51. class Proxy :public IGiveGift  
  52. {  
  53. private:  
  54.     Pursuit gg;  
  55. public:  
  56.     Proxy(SchoolGirl mm) :gg(mm)  
  57.     {  
  58.         //gg=g;  
  59.     }  
  60.     void giveDolls()  
  61.     {  
  62.         gg.giveDolls();  
  63.     }  
  64.     void giveFlowers()  
  65.     {  
  66.         gg.giveFlowers();  
  67.     }  
  68. };  
  69.   
  70. int mai12312321n()  
  71. {  
  72.     SchoolGirl lijiaojiao;  
  73.     lijiaojiao.name = "李娇娇";  
  74.     Pursuit zhuojiayi(lijiaojiao);  
  75.     Proxy daili(lijiaojiao);  
  76.   
  77.     daili.giveDolls();  
  78.     cin.get();  
  79.     return 0;  
  80. }  

单例模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. //单例模式:单例模式确保某一个类只有一个实例,  
  5. //而且自行实例化并向整个系统提供这个实例单例模式  
  6. //。单例模式只应在有真正的“单一实例”的需求时才可使用。  
  7. //俺有6个漂亮的老婆,她们的老公都是我,  
  8. //我就是我们家里的老公Sigleton,她们只要说道“老公”,  
  9. //都是指的同一个人,那就是我(刚才做了个梦啦,哪有这么好的事)。  
  10. //#define  public private   
  11.   
  12. class   
  13. {  
  14. public:  
  15. protected:  
  16. private:  
  17. }a1;  
  18.   
  19. class Singleton  
  20. {  
  21. private:  
  22.     int i;  
  23.     static Singleton *instance;  
  24.     Singleton(int i)  
  25.     {  
  26.         this->i = i;  
  27.     }  
  28. public:  
  29.     static Singleton *getInstance()  
  30.     {  
  31.         return instance;  
  32.     }  
  33.     void show()  
  34.     {  
  35.         cout << i << endl;  
  36.     }  
  37. };  
  38. Singleton* Singleton::instance = new Singleton(8899);  
  39.   
  40. class A :public Singleton  
  41. {  
  42.   
  43. };  
  44.   
  45. int mainJ()  
  46. {  
  47.     Singleton *s = Singleton::getInstance();  
  48.     Singleton *s2 = A::getInstance();  
  49.     cout << (s == s2) << endl;  
  50.     cin.get();  
  51.     return 0;  
  52. }  

迭代器模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. //迭代子模式:迭代子模式可以顺序访问一个聚集中的元素而不必暴露聚集的内部表象。  
  5. //多个对象聚在一起形成的总体称之为聚集,聚集对象是能够包容一组对象的容器对象。  
  6. //迭代子模式将迭代逻辑封装到一个独立的子对象中,从而与聚集本身隔开。  
  7. //迭代子模式简化了聚集的界面。  
  8. //每一个聚集对象都可以有一个或一个以上的迭代子对象,  
  9. //每一个迭代子的迭代状态可以是彼此独立的。  
  10. //迭代算法可以独立于聚集角色变化。  
  11. //我爱上了Mary,不顾一切的向她求婚。Mary:  
  12. //“想要我跟你结婚,得答应我的条件” 我:“什么条件我都答应,你说吧”  
  13. //Mary:“我看上了那个一克拉的钻石” 我:“我买,我买,还有吗?”  
  14. //Mary:“我看上了湖边的那栋别墅” 我:“我买,我买,还有吗?”  
  15. //Mary:“我看上那辆法拉利跑车” 我脑袋嗡的一声,坐在椅子上,一咬牙:  
  16. //“我买,我买,还有吗?” ……  
  17. class Iterator;  
  18.   
  19. class Aggregate  
  20. {  
  21. public:  
  22.     virtual Iterator *createIterator() = 0;  
  23. };  
  24.   
  25. class Iterator  
  26. {  
  27. public:  
  28.     virtual void first() = 0;  
  29.     virtual void next() = 0;  
  30.     virtual bool isDone() = 0;  
  31.     virtual bool isDoneA() = 0;  
  32.     //virtual bool isDoneA() = 0;  
  33. };  
  34.   
  35. class ConcreteAggregate :public Iterator  
  36. {  
  37. public:  
  38.     void first()  
  39.     {  
  40.       
  41.     }  
  42.     void next()  
  43.     {  
  44.     }  
  45.     bool isDone()  
  46.     {  
  47.       
  48.     }     
  49.     virtual bool isDoneA()  
  50.     {  
  51.   
  52.     }  
  53. };  
  54.   
  55.   
  56. int main12323I()  
  57. {  
  58.   
  59.     cin.get();  
  60.     return 0;  
  61. }  

访问者模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <list>  
  3. #include <string>  
  4. using namespace std;  
  5. //访问者模式:访问者模式的目的是封装一些施加于某种数据结构元素之上的操作。  
  6. //一旦这些操作需要修改的话,接受这个操作的数据结构可以保持不变。  
  7. //访问者模式适用于数据结构相对未定的系统,  
  8. //它把数据结构和作用于结构上的操作之间的耦合解脱开,  
  9. //使得操作集合可以相对自由的演化。访问者模式使得增加新的操作变的很容易,  
  10. //就是增加一个新的访问者类。  
  11. //访问者模式将有关的行为集中到一个访问者对象中,  
  12. //而不是分散到一个个的节点类中。当使用访问者模式时,  
  13. //要将尽可能多的对象浏览逻辑放在访问者类中,而不是放到它的子类中。  
  14. //访问者模式可以跨过几个类的等级结构访问属于不同的等级结构的成员类。  
  15. //情人节到了,要给每个MM送一束鲜花和一张卡片,  
  16. //可是每个MM送的花都要针对她个人的特点,每张卡片也要根据个人的特点来挑,  
  17. //我一个人哪搞得清楚,还是找花店老板和礼品店老板做一下Visitor,  
  18. //让花店老板根据MM的特点选一束花,让礼品店老板也根据每个人特点选一张卡,  
  19. //这样就轻松多了。  
  20. //访问者模式不需要改变基类,不依赖虚函数,  
  21.   
  22. class Person  
  23. {  
  24. public:  
  25.     char * action;  
  26.     virtual void getConclusion()  
  27.     {  
  28.   
  29.     };  
  30. };  
  31.   
  32. class Man :public Person  
  33. {  
  34. public:  
  35.   
  36.     void getConclusion()  
  37.     {  
  38.         if (action == "成功")  
  39.         {  
  40.             cout << "男人成功时,背后多半有一个伟大的女人。" << endl;  
  41.         }  
  42.         else if (action == "恋爱")  
  43.         {  
  44.             cout << "男人恋爱时,凡事不懂装懂。" << endl;  
  45.         }  
  46.     }  
  47. };  
  48.   
  49. class Woman :public Person  
  50. {  
  51. public:  
  52.   
  53.     void getConclusion()  
  54.     {  
  55.         if (action == "成功")  
  56.         {  
  57.             cout << "女人成功时,背后多半有失败的男人。" << endl;  
  58.         }  
  59.         else if (action == "恋爱")  
  60.         {  
  61.             cout << "女人恋爱时,遇到事懂也装不懂。" << endl;  
  62.         }  
  63.     }  
  64. };  
  65.   
  66. int main132123()  
  67. {  
  68.     list<Person*> persons;  
  69.   
  70.     Person *man1 = new Man();  
  71.     man1->action = "成功";  
  72.     persons.push_back(man1);  
  73.   
  74.     Person *woman1 = new Woman();  
  75.     woman1->action = "成功";  
  76.     persons.push_back(woman1);  
  77.   
  78.     Person *man2 = new Man();  
  79.     man2->action = "恋爱";  
  80.     persons.push_back(man2);  
  81.   
  82.     Person *woman2 = new Woman();  
  83.     woman2->action = "恋爱";  
  84.     persons.push_back(woman2);  
  85.   
  86.     list<Person*>::iterator iter = persons.begin();  
  87.     while (iter != persons.end())  
  88.     {  
  89.         (*iter)->getConclusion();  
  90.         ++iter;  
  91.     }  
  92.   
  93.     cin.get();  
  94.     return 0;  
  95. }  

观察者模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <list>  
  4. using namespace std;  
  5.   
  6. //观察者模式:观察者模式定义了一种一队多的依赖关系,  
  7. //让多个观察者对象同时监听某一个主题对象。  
  8. //这个主题对象在状态上发生变化时,会通知所有观察者对象,  
  9. //使他们能够自动更新自己。  
  10. //想知道咱们公司最新MM情报吗?加入公司的MM情报邮件组就行了,  
  11. //tom负责搜集情报,他发现的新情报不用一个一个通知我们,  
  12. //直接发布给邮件组,我们作为订阅者(观察者)就可以及时收到情报啦。  
  13. // 监视,观察者,都有一个基类,派生,实现不同的效果  
  14. //监视者的类,管理所有的观察者,增加或者删除,发出消息,让观察者处理  
  15. //观察者的类需要接受消息并处理  
  16.   
  17. class Subject; //可以使用subject  
  18.   
  19. class Observer  
  20. {  
  21. protected:  
  22.     string name;  
  23.     Subject *sub;  
  24. public:  
  25.     Observer(string name, Subject *sub)//观察者的名字, 监视与通知的类  
  26.     {  
  27.         this->name = name;//输入名字  
  28.         this->sub = sub;//设置谁来通知我  
  29.     }  
  30.     virtual void update() = 0;//纯虚函数  
  31. };  
  32.   
  33. class StockObserver :public Observer //继承,自己实现刷新函数  
  34. {  
  35. public:  
  36.     StockObserver(string name, Subject *sub) :Observer(name, sub)  
  37.     {  
  38.     }  
  39.     void update();  
  40. };  
  41.   
  42. class NBAObserver :public Observer  
  43. {  
  44. public:  
  45.     NBAObserver(string name, Subject *sub) :Observer(name, sub)  
  46.     {  
  47.     }  
  48.     void update();  
  49. };  
  50.   
  51. class Subject  //  
  52. {  
  53. protected:  
  54.     list<Observer*> observers;///存储观察者的指针,链表  
  55. public:  
  56.     string action;  
  57.     virtual void attach(Observer*) = 0;  
  58.     virtual void detach(Observer*) = 0;  
  59.     virtual void notify() = 0;//实现监听的基类  
  60. };  
  61.   
  62. class Secretary :public Subject     
  63. {  
  64.     void attach(Observer *observer)  //载入通知的列表  
  65.     {  
  66.         observers.push_back(observer);  
  67.     }  
  68.     void detach(Observer *observer)//删除  
  69.     {  
  70.         list<Observer *>::iterator iter = observers.begin();  
  71.         while (iter != observers.end())  
  72.         {  
  73.             if ((*iter) == observer)  
  74.             {  
  75.                 observers.erase(iter);  
  76.             }  
  77.             ++iter;  
  78.         }  
  79.     }  
  80.     void notify()  ///通知函数  
  81.     {  
  82.         list<Observer *>::iterator iter = observers.begin();  
  83.         while (iter != observers.end())  
  84.         {  
  85.             (*iter)->update();  
  86.             ++iter;  
  87.         }  
  88.     }  
  89. };  
  90.   
  91. void StockObserver::update()  
  92. {  
  93.     cout << name << " 收到消息:" << sub->action << endl;  
  94.     if (sub->action == "梁所长来了!")  
  95.     {  
  96.         cout << "我马上关闭股票,装做很认真工作的样子!" << endl;  
  97.     }  
  98.     if (sub->action == "去喝酒!")  
  99.     {  
  100.         cout << "我马上走" << endl;  
  101.     }  
  102. }  
  103.   
  104. void NBAObserver::update()  
  105. {  
  106.     cout << name << " 收到消息:" << sub->action << endl;  
  107.     if (sub->action == "梁所长来了!")  
  108.     {  
  109.         cout << "我马上关闭NBA,装做很认真工作的样子!" << endl;  
  110.     }  
  111.   
  112.    if (sub->action == "去喝酒!")  
  113.    {  
  114.     cout << "我马上拍" << endl;  
  115.     }  
  116. }  
  117.   
  118. int main123123()  
  119. {  
  120.     Subject *dwq = new Secretary();//消息监视,监视  
  121.   
  122.     Observer *xs = new NBAObserver("xiaoshuai", dwq);//订阅消息  
  123.     Observer *zy = new NBAObserver("zouyue", dwq);  
  124.     Observer *lm = new StockObserver("limin", dwq);  
  125.   
  126.     dwq->attach(xs);  
  127.     dwq->attach(zy);  
  128.     dwq->attach(lm);//增加到队列  
  129.   
  130.     dwq->action = "去吃饭了!";  
  131.     dwq->notify();  
  132.     dwq->action = "去喝酒!";  
  133.     dwq->notify();  
  134.     cout << endl;  
  135.     dwq->action = "梁所长来了!";  
  136.     dwq->notify();  
  137.     cin.get();  
  138.     return 0;  
  139. }  

建造者模式

[java]  view plain  copy
  1. #include <string>  
  2. #include <iostream>  
  3. #include <vector>  
  4. using namespace std;  
  5. //建造模式:将产品的内部表象和产品的生成过程分割开来,  
  6. //从而使一个建造过程生成具有不同的内部表象的产品对象。  
  7. //建造模式使得产品内部表象可以独立的变化,  
  8. //客户不必知道产品内部组成的细节。  
  9. //建造模式可以强制实行一种分步骤进行的建造过程。  
  10. //MM最爱听的就是“我爱你”这句话了,见到不同地方的MM,  
  11. //要能够用她们的方言跟她说这句话哦,我有一个多种语言翻译机,  
  12. //上面每种语言都有一个按键,见到MM我只要按对应的键,  
  13. //它就能够用相应的语言说出“我爱你”这句话了,  
  14. //国外的MM也可以轻松搞掂,这就是我的“我爱你”builder。(  
  15. //这一定比美军在伊拉克用的翻译机好卖)  
  16.   
  17. class Person  //抽象类,预留ule接口  
  18. {  
  19. public:  
  20.     virtual void createHead() = 0;  
  21.     virtual void createHand() = 0;  
  22.     virtual void createBody() = 0;  
  23.     virtual void createFoot() = 0;  
  24. };  
  25.   
  26. class ThinPerson :public Person  ///实现抽象类瘦子,  
  27. {  
  28.     void createHead()  
  29.     {  
  30.         cout << "thin head" << endl;  
  31.     }  
  32.     void createHand()  
  33.     {  
  34.         cout << "thin hand" << endl;  
  35.     }  
  36.     void createBody()  
  37.     {  
  38.         cout << "thin body" << endl;  
  39.     }  
  40.     void createFoot()  
  41.     {  
  42.         cout << "thin foot" << endl;  
  43.     }  
  44. };  
  45.   
  46. class FatPerson :public Person //胖子  
  47. {  
  48.     void createHead()  
  49.     {  
  50.         cout << "fat head" << endl;  
  51.     }  
  52.     void createHand()  
  53.     {  
  54.         cout << "fat hand" << endl;  
  55.     }  
  56.     void createBody()  
  57.     {  
  58.         cout << "fat body" << endl;  
  59.     }  
  60.     void createFoot()  
  61.     {  
  62.         cout << "fat foot" << endl;  
  63.     }  
  64. };  
  65.   
  66.   
  67. class Director  
  68. {  
  69. private:  
  70.     Person *p;//基类的指针  
  71. public:  
  72.     Director(Person *temp) //传递对象  
  73.     {  
  74.         p = temp;//虚函数实现多态  
  75.     }  
  76.     void create()  
  77.     {  
  78.         p->createHead();  
  79.         p->createHand();  
  80.         p->createBody();  
  81.         p->createFoot();  
  82.     }  
  83. };  
  84.   
  85. //客户端代码:  
  86. int mainT()  
  87. {  
  88.     Person *p = new FatPerson();  
  89.   
  90.     Director *d = new Director(p);  
  91.     d->create();  
  92.     delete d;  
  93.     delete p;  
  94.   
  95.     cin.get();  
  96.     return 0;  
  97. }  

解释器模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <list>  
  3. #include <string>  
  4. using namespace std;  
  5. //解释器模式:给定一个语言后,解释器模式可以定义出其文法的一种表示,  
  6. //并同时提供一个解释器。客户端可以使用这个解释器来解释这个语言中的句子。  
  7. //解释器模式将描述怎样在有了一个简单的文法后,使用模式设计解释这些语句。  
  8. //在解释器模式里面提到的语言是指任何解释器对象能够解释的任何组合。  
  9. //在解释器模式中需要定义一个代表文法的命令类的等级结构,  
  10. //也就是一系列的组合规则。每一个命令对象都有一个解释方法,  
  11. //代表对命令对象的解释。命令对象的等级结构中的对象的任何排列组合都是一个语言。  
  12. //俺有一个《泡MM真经》,上面有各种泡MM的攻略,比如说去吃西餐的步骤、  
  13. //去看电影的方法等等,跟MM约会时,只要做一个Interpreter,  
  14. //照着上面的脚本执行就可以了。  
  15.   
  16. class Context;  
  17.   
  18. class AbstractExpression  
  19. {  
  20. public:  
  21.     virtual void interpret(Context *) = 0;  
  22. };  
  23.   
  24. class TerminalExpression :public AbstractExpression  
  25. {  
  26. public:  
  27.     void interpret(Context *context)  
  28.     {  
  29.         cout << "终端解释器" << endl;  
  30.     }  
  31. };  
  32.   
  33. class NonterminalExpression :public AbstractExpression  
  34. {  
  35. public:  
  36.     void interpret(Context *context)  
  37.     {  
  38.         cout << "非终端解释器" << endl;  
  39.     }  
  40. };  
  41.   
  42. class Context  
  43. {  
  44. public:  
  45.     string input, output;  
  46. };  
  47.   
  48. int mainK()  
  49. {  
  50.     Context *context = new Context();  
  51.     list<AbstractExpression*>  lt;  
  52.     lt.push_back(new TerminalExpression());  
  53.     lt.push_back(new NonterminalExpression());  
  54.     lt.push_back(new TerminalExpression());  
  55.     lt.push_back(new TerminalExpression());  
  56.   
  57.     for (list<AbstractExpression*>::iterator iter = lt.begin(); iter != lt.end(); iter++)  
  58.     {  
  59.         (*iter)->interpret(context);  
  60.     }  
  61.   
  62.     cin.get();  
  63.     return 0;  
  64. }  

命令模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <list>  
  4. //命令模式:命令模式把一个请求或者操作封装到一个对象中。  
  5. //命令模式把发出命令的责任和执行命令的责任分割开,委派给不同的对象。  
  6. //命令模式允许请求的一方和发送的一方独立开来,  
  7. //使得请求的一方不必知道接收请求的一方的接口,  
  8. //更不必知道请求是怎么被接收,  
  9. //以及操作是否执行,何时被执行以及是怎么被执行的。  
  10. //系统支持命令的撤消。  
  11. //俺有一个MM家里管得特别严,没法见面,只好借助于她弟弟在我们俩之间传送信息,  
  12. //她对我有什么指示,就写一张纸条让她弟弟带给我。这不,  
  13. //她弟弟又传送过来一个COMMAND,为了感谢他,我请他吃了碗杂酱面,  
  14. //哪知道他说:“我同时给我姐姐三个男朋友送COMMAND,就数你最小气,  
  15. //才请我吃面。”  
  16. //  
  17. using namespace std;  
  18.   
  19. class Barbecuer  //接收者执行命令  
  20. {  
  21. public:  
  22.     void bakeMutton()  
  23.     {  
  24.         cout << "烤羊肉串" << endl;  
  25.     }  
  26.     void bakeChickenWing()  
  27.     {  
  28.         cout << "烤鸡翅" << endl;  
  29.     }  
  30. };  
  31.   
  32. class Command   //命令基类  
  33. {  
  34. protected:  
  35.     Barbecuer *receiver;//类的包含  
  36. public:  
  37.     Command(Barbecuer *receiver)//命令接受  
  38.     {  
  39.         this->receiver = receiver;  
  40.     }  
  41.     virtual void executeCommand() = 0;  
  42. };  
  43.   
  44. class BakeMuttonCommand :public Command  //命令传送着  
  45. {  
  46. public:  
  47.     BakeMuttonCommand(Barbecuer *receiver) :Command(receiver)  
  48.     {}  
  49.     void executeCommand()  
  50.     {  
  51.         receiver->bakeMutton();  
  52.     }  
  53. };  
  54.   
  55. class BakeChikenWingCommand :public Command  //命令传送着  
  56. {  
  57. public:  
  58.     BakeChikenWingCommand(Barbecuer *receiver) :Command(receiver)  
  59.     {}  
  60.     void executeCommand()  
  61.     {  
  62.         receiver->bakeChickenWing();  
  63.     }  
  64. };  
  65.   
  66. class Waiter        //服务员  
  67. {  
  68. private:  
  69.     Command *command;  
  70. public:  
  71.     void setOrder(Command *command)  
  72.     {  
  73.         this->command = command;  
  74.     }  
  75.     void notify()  
  76.     {  
  77.         command->executeCommand();  
  78.     }  
  79. };  
  80.   
  81. class Waiter2   //gei多个对象下达命令  
  82. {  
  83. private:  
  84.     list<Command*> orders;  
  85. public:  
  86.     void setOrder(Command *command)  
  87.     {  
  88.         orders.push_back(command);  
  89.     }  
  90.     void cancelOrder(Command *command)  
  91.     {}  
  92.     void notify()  
  93.     {  
  94.         list<Command*>::iterator iter = orders.begin();  
  95.         while (iter != orders.end())  
  96.         {  
  97.             (*iter)->executeCommand();  
  98.             iter++;  
  99.         }  
  100.     }  
  101. };  
  102.   
  103.   
  104. int main1232131231()  
  105. {  
  106.   
  107.     Barbecuer *boy = new Barbecuer();  
  108.     Command *bm1 = new BakeMuttonCommand(boy);  
  109.     Command *bm2 = new BakeMuttonCommand(boy);  
  110.     Command *bc1 = new BakeChikenWingCommand(boy);  
  111.   
  112.     Waiter2 *girl = new Waiter2();  
  113.   
  114.     girl->setOrder(bm1);  
  115.     girl->setOrder(bm2);  
  116.     girl->setOrder(bc1);  
  117.   
  118.     girl->notify();  
  119.   
  120.   
  121.     cin.get();  
  122.   
  123.     return 0;  
  124. }  

模板模式

[java]  view plain  copy
  1. #include<iostream>  
  2. #include <vector>  
  3. #include <string>  
  4. using namespace std;  
  5. /*模板方法模式:模板方法模式准备一个抽象类, 
  6. 将部分逻辑以具体方法以及具体构造子的形式实现, 
  7. 然后声明一些抽象方法来迫使子类实现剩余的逻辑。 
  8. 不同的子类可以以不同的方式实现这些抽象方法, 
  9. 从而对剩余的逻辑有不同的实现。先制定一个顶级逻辑框架, 
  10. 而将逻辑的细节留给具体的子类去实现。 
  11.  
  12. 女生从认识到得手的不变的步骤分为巧遇、打破僵局、展开追求、接吻、得手 
  13. 但每个步骤针对不同的情况,都有不一样的做法,这就要看你随机应变啦(具体实现)*/  
  14.   
  15. class AbstractClass  
  16. {  
  17. public:  
  18.     void Show()  
  19.     {  
  20.         cout << "我是" << GetName() << endl;  
  21.     }  
  22. protected:  
  23.     virtual string GetName() = 0;  
  24. };  
  25.   
  26. class Naruto : public AbstractClass  
  27. {  
  28. protected:  
  29.     virtual string GetName()  
  30.     {  
  31.         return "火影史上最帅的六代目---一鸣惊人naruto";  
  32.     }  
  33. };  
  34.   
  35. class OnePice : public AbstractClass  
  36. {  
  37. protected:  
  38.     virtual string GetName()  
  39.     {  
  40.         return "我是无恶不做的大海贼---路飞";  
  41.     }  
  42. };  
  43.   
  44. //客户端  
  45. int mainP13()  
  46. {  
  47.     Naruto* man = new Naruto();  
  48.     man->Show();  
  49.   
  50.     OnePice* man2 = new OnePice();  
  51.     man2->Show();  
  52.   
  53.     cin.get();  
  54.     return 0;  
  55. }  

桥接模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. //桥梁模式:将抽象化与实现化脱耦,使得二者可以独立的变化,  
  5. //也就是说将他们之间的强关联变成弱关联,  
  6. //也就是指在一个软件系统的抽象化和实现化之间使用组合   
  7. /// 聚合关系而不是继承关系,从而使两者可以独立的变化。  
  8. //早上碰到MM,要说早上好,晚上碰到MM,要说晚上好;  
  9. //碰到MM穿了件新衣服,要说你的衣服好漂亮哦,碰到MM新做的发型,  
  10. //要说你的头发好漂亮哦。不要问我“早上碰到MM新做了个发型怎么说”  
  11. //这种问题,自己用BRIDGE组合一下不就行了。  
  12.   
  13. class HandsetSoft  
  14. {  
  15. public:  
  16.     virtual void run() = 0;  
  17. };  
  18.   
  19. class HandsetGame :public HandsetSoft  
  20. {  
  21. public:  
  22.     void run()  
  23.     {  
  24.         cout << "运行手机游戏" << endl;  
  25.     }  
  26. };  
  27.   
  28. class HandsetAddressList :public HandsetSoft  
  29. {  
  30. public:  
  31.     void run()  
  32.     {  
  33.         cout << "运行手机通讯录" << endl;  
  34.     }  
  35. };  
  36.   
  37. class HandsetBrand  
  38. {  
  39. protected:  
  40.     HandsetSoft *soft;  
  41. public:  
  42.     void setHandsetSoft(HandsetSoft *soft)  
  43.     {  
  44.         this->soft = soft;  
  45.     }  
  46.     virtual void run() = 0;  
  47. };  
  48.   
  49. class HandsetBrandN :public HandsetBrand  
  50. {  
  51. public:  
  52.     void run()  
  53.     {  
  54.         soft->run();  
  55.     }  
  56. };  
  57.   
  58. class HandsetBrandM :public HandsetBrand  
  59. {  
  60. public:  
  61.     void run()  
  62.     {  
  63.         soft->run();  
  64.     }  
  65. };  
  66.   
  67. int mainS()  
  68. {  
  69.     HandsetBrand *hb;  
  70.     hb = new HandsetBrandM();  
  71.   
  72.     hb->setHandsetSoft(new HandsetGame());  
  73.     hb->run();  
  74.     hb->setHandsetSoft(new HandsetAddressList());  
  75.     hb->run();  
  76.   
  77.     cin.get();  
  78.     return 0;  
  79. }  

适配器模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. //适配器(变压器)模式:把一个类的接口变换成客户端所期待的另一种接口  
  5. //,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。  
  6. //适配类可以根据参数返还一个合适的实例给客户端。  
  7. //  
  8. //在朋友聚会上碰到了一个美女Sarah,从香港来的,  
  9. //可我不会说粤语,她不会说普通话,只好求助于我的朋友kent了,  
  10. //他作为我和Sarah之间的Adapter,让我和Sarah可以相互交谈了  
  11. //(也不知道他会不会耍我)。  
  12.   
  13. class Player  
  14. {  
  15. public:  
  16.     string name;  
  17.     Player(string name)  
  18.     {  
  19.         this->name = name;  
  20.     }  
  21.     virtual void attack() = 0;  
  22.     virtual void defence() = 0;  
  23. };  
  24.   
  25. class Forwards :public Player  
  26. {  
  27. public:  
  28.     Forwards(string name) :Player(name){}  
  29.     void attack()  
  30.     {  
  31.         cout << name << " 前锋进攻" << endl;  
  32.     }  
  33.     void defence()  
  34.     {  
  35.         cout << name << " 前锋防守" << endl;  
  36.     }  
  37. };  
  38.   
  39. class Center :public Player  
  40. {  
  41. public:  
  42.     Center(string name) :Player(name){}  
  43.     void attack()  
  44.     {  
  45.         cout << name << " 中锋进攻" << endl;  
  46.     }  
  47.     void defence()  
  48.     {  
  49.         cout << name << " 中锋防守" << endl;  
  50.     }  
  51. };  
  52.   
  53. class Backwards :public Player  
  54. {  
  55. public:  
  56.     Backwards(string name) :Player(name){}  
  57.     void attack()  
  58.     {  
  59.         cout << name << " 后卫进攻" << endl;  
  60.     }  
  61.     void defence()  
  62.     {  
  63.         cout << name << " 后卫防守" << endl;  
  64.     }  
  65. };  
  66. /*****************************************************************/  
  67. class ForeignCenter  
  68. {  
  69. public:  
  70.     string name;  
  71.     ForeignCenter(string name)  
  72.     {  
  73.         this->name = name;  
  74.     }  
  75.     void myAttack()  
  76.     {  
  77.         cout << name << " 外籍中锋进攻" << endl;  
  78.     }  
  79.     void myDefence()  
  80.     {  
  81.         cout << name << " 外籍后卫防守" << endl;  
  82.     }  
  83. };  
  84. /*****************************************************************/  
  85. class Translator :public Player  
  86. {  
  87. private:  
  88.     ForeignCenter *fc;  
  89. public:  
  90.     Translator(string name) :Player(name)  
  91.     {  
  92.         fc = new ForeignCenter(name);  
  93.     }  
  94.     void attack()  
  95.     {  
  96.         fc->myAttack();  
  97.     }  
  98.     void defence()  
  99.     {  
  100.         fc->myDefence();  
  101.     }  
  102. };  
  103. /*****************************************************************/  
  104. int mainM()  
  105. {  
  106.     Player *p1 = new Center("李俊宏");  
  107.     p1->attack();  
  108.     p1->defence();  
  109.   
  110.     Translator *tl = new Translator("姚明");  
  111.     tl->attack();  
  112.     tl->defence();  
  113.     cin.get();  
  114.     return 0;  
  115. }  

外观模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. //门面模式:外部与一个子系统的通信必须通过一个统一的门面对象进行。  
  5. //门面模式提供一个高层次的接口,使得子系统更易于使用。  
  6. //每一个子系统只有一个门面类,而且此门面类只有一个实例,  
  7. //也就是说它是一个单例模式。但整个系统可以有多个门面类。  
  8. //  
  9. //我有一个专业的Nikon相机,我就喜欢自己手动调光圈、快门,  
  10. //这样照出来的照片才专业,但MM可不懂这些,教了半天也不会。  
  11. //幸好相机有Facade设计模式,把相机调整到自动档,  
  12. //只要对准目标按快门就行了,一切由相机自动调整,  
  13. //这样MM也可以用这个相机给我拍张照片了。  
  14.   
  15. class Sub1  
  16. {  
  17. public:  
  18.     void f1()  
  19.     {  
  20.         cout << "子系统的方法 1" << endl;  
  21.     }  
  22. };  
  23.   
  24. class Sub2  
  25. {  
  26. public:  
  27.     void f2()  
  28.     {  
  29.         cout << "子系统的方法 2" << endl;  
  30.     }  
  31. };  
  32.   
  33. class Sub3  
  34. {  
  35. public:  
  36.     void f3()  
  37.     {  
  38.         cout << "子系统的方法 3" << endl;  
  39.     }  
  40. };  
  41.   
  42. class Facade  
  43. {  
  44. private:  
  45.     Sub1 *s1;  
  46.     Sub2 *s2;  
  47.     Sub3 *s3;  
  48. public:  
  49.     Facade()  
  50.     {  
  51.         s1 = new Sub1();  
  52.         s2 = new Sub2();  
  53.         s3 = new Sub3();  
  54.     }  
  55.     void method()  
  56.     {  
  57.         s1->f1();  
  58.         s2->f2();  
  59.         s3->f3();  
  60.     }  
  61. };  
  62.   
  63. int mainB ()  
  64. {  
  65.     Facade *f = new Facade();  
  66.     f->method();   
  67.     cin.get();  
  68.     return 0;  
  69. }  

享元模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <list>  
  3. #include <string>  
  4. #include <map>  
  5. using namespace std;  
  6.   
  7. //享元模式:FLYWEIGHT在拳击比赛中指最轻量级。  
  8. //享元模式以共享的方式高效的支持大量的细粒度对象。  
  9. //享元模式能做到共享的关键是区分内蕴状态和外蕴状态。  
  10. //内蕴状态存储在享元内部,不会随环境的改变而有所不同。  
  11. //外蕴状态是随环境的改变而改变的。外蕴状态不能影响内蕴状态,  
  12. //它们是相互独立的。将可以共享的状态和不可以共享的状态从常规类中区分开来,  
  13. //将不可以共享的状态从类里剔除出去。客户端不可以直接创建被共享的对象,  
  14. //而应当使用一个工厂对象负责创建被共享的对象。  
  15. //享元模式大幅度的降低内存中对象的数量。  
  16. //  
  17. //每天跟MM发短信,手指都累死了,最近买了个新手机,  
  18. //可以把一些常用的句子存在手机里,要用的时候,直接拿出来  
  19. //,在前面加上MM的名字就可以发送了,再不用一个字一个字敲了。  
  20. //共享的句子就是Flyweight,MM的名字就是提取出来的外部特征,  
  21. //根据上下文情况使用。  
  22.   
  23. class WebSite  
  24. {  
  25. public:  
  26.     virtual void use() = 0;//预留接口实现功能  
  27. };  
  28.   
  29. class ConcreteWebSite :public WebSite  
  30. {  
  31. private:  
  32.     string name;  
  33. public:  
  34.     ConcreteWebSite(string name)//实例化  
  35.     {  
  36.         this->name = name;  
  37.     }  
  38.     void use()  
  39.     {  
  40.         cout << "网站分类: " << name << endl;  
  41.     }  
  42. };  
  43.   
  44. class WebSiteFactory  
  45. {  
  46. private:  
  47.     map<string, WebSite*> wf;  
  48. public:  
  49.   
  50.     WebSite *getWebSiteCategory(string key)  
  51.     {  
  52.   
  53.         if (wf.find(key) == wf.end())  
  54.         {  
  55.             wf[key] = new ConcreteWebSite(key);  
  56.         }  
  57.   
  58.         return wf[key];  
  59.     }  
  60.   
  61.     int getWebSiteCount()  
  62.     {  
  63.         return wf.size();  
  64.     }  
  65. };  
  66.   
  67. int main123qweqe()  
  68. {  
  69.     WebSiteFactory *wf = new WebSiteFactory();  
  70.   
  71.     WebSite *fx = wf->getWebSiteCategory("good");  
  72.     fx->use();  
  73.   
  74.     WebSite *fy = wf->getWebSiteCategory("产品展示");  
  75.     fy->use();  
  76.   
  77.     WebSite *fz = wf->getWebSiteCategory("产品展示");  
  78.     fz->use();  
  79.   
  80.   
  81.     WebSite *f1 = wf->getWebSiteCategory("博客");  
  82.     f1->use();  
  83.   
  84.     WebSite *f2 = wf->getWebSiteCategory("博客");  
  85.     f2->use();  
  86.   
  87.     cout << wf->getWebSiteCount() << endl;  
  88.   
  89.     cin.get();  
  90.     return 0;  
  91. }  

原型模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. //原型模式允许动态的增加或减少产品类,  
  5. //产品类不需要非得有任何事先确定的等级结构,  
  6. //原始模型模式适用于任何的等级结构。  
  7. //缺点是每一个类都必须配备一个克隆方法。  
  8.   
  9.   
  10. //跟MM用QQ聊天,一定要说些深情的话语了,  
  11. //我搜集了好多肉麻的情话,需要时只要copy出来放到QQ里面就行了,  
  12. //这就是我的情话prototype了。  
  13. //原型模式:通过给出一个原型对象来指明所要创建的对象的类型,  
  14. //然后用复制这个原型对象的方法创建出更多同类型的对象。  
  15.   
  16. class Resume  
  17. {  
  18. private:  
  19.     string name, sex, age, timeArea, company;  
  20. public:  
  21.     Resume(string s)  
  22.     {  
  23.         name = s;  
  24.     }  
  25.     void setPersonalInfo(string s, string a)  
  26.     {  
  27.         sex = s;  
  28.         age = a;  
  29.     }  
  30.     void setWorkExperience(string t, string c)  
  31.     {  
  32.         timeArea = t;  
  33.         company = c;  
  34.     }  
  35.     void display()  
  36.     {  
  37.         cout << name << "  " << sex << "  " << age << endl;  
  38.         cout << "工作经历:  " << timeArea << "  " << company << endl << endl;  
  39.   
  40.     }  
  41.     Resume *clone()  
  42.     {  
  43.         Resume *b;  
  44.         b = new Resume(name);  
  45.         b->setPersonalInfo(sex, age);  
  46.         b->setWorkExperience(timeArea, company);  
  47.         return b;  
  48.     }  
  49. };  
  50.   
  51.   
  52. int main213123()  
  53. {  
  54.     Resume *r = new Resume("李彦宏");  
  55.     r->setPersonalInfo("男""30");  
  56.     r->setWorkExperience("2007-2010""读研究生");  
  57.     r->display();  
  58.   
  59.   
  60.     Resume *r2 = r->clone();  
  61.     r2->setWorkExperience("2003-2007""读本科");  
  62.   
  63.     r->display();  
  64.     r2->display();  
  65.   
  66.     cin.get();  
  67.     return 0;  
  68. }  

责任链模式

[java]  view plain  copy
  1. #include<iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. //责任链模式:在责任链模式中,很多对象由每一个对象对其下家的引用而接起来形成  
  6. //一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。  
  7. //客户并不知道链上的哪一个对象最终处理这个请求,系统可以在不影响客户端的  
  8. //情况下动态的重新组织链和分配责任。处理者有两个选择:承担责任或者把责任  
  9. //推给下家。一个请求可以最终不被任何接收端对象所接受。  
  10. //  
  11. //晚上去上英语课,为了好开溜坐到了最后一排,哇,前面坐了好几个漂亮的MM哎,  
  12. //找张纸条,写上“Hi, 可以做我的女朋友吗?如果不愿意请向前传”,  
  13. //纸条就一个接一个的传上去了,糟糕,传到第一排的MM把纸条传给老师了,  
  14. //听说是个老处女呀,快跑!  
  15.   
  16. class Request  //请求  
  17. {  
  18. public:  
  19.     string requestType;  
  20.     string requestContent;  
  21.     int number;  
  22. };  
  23.   
  24. class Manager  ///管理者  
  25. {  
  26. protected:  
  27.     string name;  
  28.     Manager *superior;  
  29. public:  
  30.     Manager(string name)  
  31.     {  
  32.         this->name = name;  
  33.     }  
  34.     void setSuperior(Manager *superior)  
  35.     {  
  36.         this->superior = superior;  
  37.     }  
  38.     virtual void requestApplications(Request *request) = 0;  
  39. };  
  40.   
  41. class CommonManager :public Manager  //经理  
  42. {  
  43. public:  
  44.     CommonManager(string name) :Manager(name)  
  45.     {}  
  46.     void requestApplications(Request *request)  
  47.     {  
  48.         if (request->requestType == "请假" && request->number <= 2)  
  49.         {  
  50.             cout << name << " " << request->requestContent << " 数量: " << request->number << "被批准" << endl;  
  51.         }  
  52.         else  
  53.         {  
  54.             if (superior != NULL)  
  55.             {  
  56.                 superior->requestApplications(request);  
  57.             }  
  58.         }  
  59.     }  
  60. };  
  61.   
  62. class Majordomo :public Manager  //总监  
  63. {  
  64. public:  
  65.     Majordomo(string name) :Manager(name)  
  66.     {}  
  67.     void requestApplications(Request *request)  
  68.     {  
  69.         if (request->requestType == "请假" && request->number <= 5)  
  70.         {  
  71.             cout << name << " " << request->requestContent << " 数量: " << request->number << "被批准" << endl;  
  72.         }  
  73.         else  
  74.         {  
  75.             if (superior != NULL)  
  76.             {  
  77.                 superior->requestApplications(request);  
  78.             }  
  79.         }  
  80.     }  
  81. };  
  82.   
  83.   
  84. class GeneralManager :public Manager //总经理  
  85. {  
  86. public:  
  87.     GeneralManager(string name) :Manager(name)  
  88.     {}  
  89.     void requestApplications(Request *request)  
  90.     {  
  91.         if (request->requestType == "请假")  
  92.         {  
  93.             cout << name << " " << request->requestContent << " 数量: " << request->number << "被批准" << endl;  
  94.         }  
  95.     }  
  96. };  
  97.   
  98.   
  99. int main123213123213()  
  100. {  
  101.     CommonManager *jinli = new CommonManager("经理");  
  102.     Majordomo *zongjian = new Majordomo("总监");  
  103.     GeneralManager *zhongjingli = new GeneralManager("总经理");  
  104.   
  105.     jinli->setSuperior(zongjian);  
  106.     zongjian->setSuperior(zhongjingli);  
  107.   
  108.     Request *request = new Request();  
  109.   
  110.     request->requestType = "请假";  
  111.     request->requestContent = "李俊宏请假";  
  112.     request->number = 1;  
  113.     jinli->requestApplications(request);  
  114.   
  115.   
  116.     request->requestType = "请假";  
  117.     request->requestContent = "李俊宏请假";  
  118.     request->number = 4;  
  119.     jinli->requestApplications(request);  
  120.   
  121.   
  122.     request->requestType = "请假";  
  123.     request->requestContent = "李俊宏请假";  
  124.     request->number = 10;  
  125.     jinli->requestApplications(request);  
  126.   
  127.     cin.get();  
  128.     return 0;  
  129. }  

中介者模式

[java]  view plain  copy
  1. #include<iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. ////MEDIATOR 调停者模式  
  5. //  
  6. ////调停者模式:调停者模式包装了一系列对象相互作用的方式,  
  7. //使得这些对象不必相互明显作用。从而使他们可以松散偶合。  
  8. //当某些对象之间的作用发生改变时,不会立即影响其他的一些对象之间的作用。  
  9. //保证这些作用可以彼此独立的变化。调停者模式将多对多的相互作用转化  
  10. //为一对多的相互作用。调停者模式将对象的行为和协作抽象化  
  11. //,把对象在小尺度的行为上与其他对象的相互作用分开处理。  
  12. //  
  13. ////四个MM打麻将,相互之间谁应该给谁多少钱算不清楚了,  
  14. //幸亏当时我在旁边,按照各自的筹码数算钱,赚了钱的从我这里拿,  
  15. //赔了钱的也付给我,一切就OK啦,俺得到了四个MM的电话。  
  16. //  
  17. ////中介者模式,找不到老婆可以相亲靠婚介  
  18.   
  19. class Country;  
  20.   
  21. class UniteNations  
  22. {  
  23. public:  
  24.     virtual void declare(string message, Country *colleague) = 0;  
  25. };  
  26.   
  27. class Country  
  28. {  
  29. protected:  
  30.     UniteNations *mediator;  
  31. public:  
  32.     Country(UniteNations *mediator)  
  33.     {  
  34.         this->mediator = mediator;  
  35.     }  
  36. };  
  37.   
  38. class USA :public Country  
  39. {  
  40. public:  
  41.     USA(UniteNations *mediator) :Country(mediator)  
  42.     {}  
  43.     void declare(string message)  
  44.     {  
  45.         cout << "美发布信息: " << message << endl;  
  46.         mediator->declare(message, this);  
  47.     }  
  48.     void getMessage(string message)  
  49.     {  
  50.         cout << "美国获得对方信息: " << message << endl;  
  51.     }  
  52. };  
  53.   
  54. class Iraq :public Country  
  55. {  
  56. public:  
  57.     Iraq(UniteNations *mediator) :Country(mediator)  
  58.     {}  
  59.     void declare(string message)  
  60.     {  
  61.         cout << "伊拉克发布信息: " << message << endl;  
  62.         mediator->declare(message, this);  
  63.     }  
  64.     void getMessage(string message)  
  65.     {  
  66.         cout << "伊拉克获得对方信息: " << message << endl;  
  67.     }  
  68. };  
  69.   
  70. class UnitedNationsSecurityCouncil :public UniteNations  
  71. {  
  72. public:  
  73.     USA *usa;  
  74.     Iraq *iraq;  
  75.     void declare(string message, Country *colleague)  
  76.     {  
  77.         if (colleague == usa)  
  78.         {  
  79.             iraq->getMessage(message);  
  80.         }  
  81.         else  
  82.         {  
  83.             usa->getMessage(message);  
  84.         }  
  85.     }  
  86. };  
  87.   
  88. int mainWERT()  
  89. {  
  90.     UnitedNationsSecurityCouncil *unsc = new UnitedNationsSecurityCouncil();  
  91.   
  92.     USA *c1 = new USA(unsc);  
  93.     Iraq *c2 = new Iraq(unsc);  
  94.   
  95.     unsc->usa = c1;  
  96.     unsc->iraq = c2;  
  97.   
  98.     c1->declare("不准开发核武器,否则打你!");  
  99.     c2->declare("他妈的美国去死!");  
  100.   
  101.     cin.get();  
  102.     return 0;  
  103. }  

装饰模式

[java]  view plain  copy
  1. #include <string>  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. //装饰模式:装饰模式以对客户端透明的方式扩展对象的功能,  
  6. //是继承关系的一个替代方案,提供比继承更多的灵活性。  
  7. //动态给一个对象增加功能,这些功能可以再动态的撤消。  
  8. //增加由一些基本功能的排列组合而产生的非常大量的功能。  
  9. //  
  10. //Mary过完轮到Sarly过生日,还是不要叫她自己挑了,  
  11. //不然这个月伙食费肯定玩完,拿出我去年在华山顶上照的照片,  
  12. //在背面写上“最好的的礼物,就是爱你的Fita”,  
  13. //再到街上礼品店买了个像框(卖礼品的MM也很漂亮哦),  
  14. //再找隔壁搞美术设计的Mike设计了一个漂亮的盒子装起来……,  
  15. //我们都是Decorator,最终都在修饰我这个人呀,怎么样,看懂了吗?  
  16.   
  17. class Person  
  18. {  
  19. private:  
  20.     string m_strName;  
  21. public:  
  22.     Person(string strName)  
  23.     {  
  24.         m_strName = strName;  
  25.     }  
  26.     Person(){}  
  27.     virtual void show()  
  28.     {  
  29.         cout << "装扮的是:" << m_strName << endl;  
  30.     }  
  31. };  
  32.   
  33. class Finery :public Person  
  34. {  
  35. protected:  
  36.     Person *m_component;  
  37. public:  
  38.     void decorate(Person* component)  
  39.     {  
  40.         m_component = component;  
  41.     }  
  42.     virtual void show()  
  43.     {  
  44.         m_component->show();  
  45.     }  
  46. };  
  47.   
  48. class TShirts :public Finery  
  49. {  
  50. public:  
  51.     virtual void show()  
  52.     {  
  53.         m_component->show();  
  54.         cout << "T shirts" << endl;  
  55.     }  
  56. };  
  57.   
  58. class BigTrouser :public Finery  
  59. {  
  60. public:  
  61.     virtual void show()  
  62.     {  
  63.         m_component->show();  
  64.         cout << "Big Trouser" << endl;  
  65.     }  
  66. };  
  67.   
  68. int mainE()  
  69. {  
  70.     Person *p = new Person("小李");  
  71.     BigTrouser *bt = new BigTrouser();  
  72.     TShirts *ts = new TShirts();  
  73.   
  74.     bt->decorate(p);  
  75.     ts->decorate(bt);  
  76.     ts->show();  
  77.     cin.get();  
  78.     return 0;  
  79. }  

状态模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4. //状态模式:状态模式允许一个对象在其内部状态改变的时候改变行为。  
  5. //这个对象看上去象是改变了它的类一样。状态模式把所研究的对象的行  
  6. //为包装在不同的状态对象里,每一个状态对象都属于一个抽象状态类的  
  7. //一个子类。状态模式的意图是让一个对象在其内部状态改变的时候,  
  8. //其行为也随之改变。状态模式需要对每一个系统可能取得的状态创立一个状态类的  
  9. //子类。当系统的状态变化时,系统便改变所选的子类。  
  10. //  
  11. //跟MM交往时,一定要注意她的状态哦,在不同的状态时她的行为会有不同,  
  12. //比如你约她今天晚上去看电影,对你没兴趣的MM就会说“有事情啦”  
  13. //,对你不讨厌但还没喜欢上的MM就会说“好啊,不过可以带上我同事么?”  
  14. //,已经喜欢上你的MM就会说“几点钟?看完电影再去泡吧怎么样?”,  
  15. //当然你看电影过程中表现良好的话,也可以把MM的状态从不讨厌不喜欢变成喜欢哦。  
  16.   
  17. class Work;  
  18. class State;  
  19. class ForenonnState;  
  20.   
  21. class State  
  22. {  
  23. public:  
  24.     virtual void writeProgram(Work*) = 0;//准柜台的基类,抽象类  
  25. };  
  26.   
  27. class Work   //实施工作的类,根据状态执行不同的操作  
  28. {  
  29. public:  
  30.     int hour;  
  31.     State *current;  
  32.     Work();  
  33.       
  34.       
  35.     void writeProgram()  
  36.     {  
  37.         current->writeProgram(this);  
  38.     }  
  39. };  
  40.   
  41. class EveningState :public State  //晚上状态  
  42. {  
  43. public:  
  44.     void writeProgram(Work *w)  
  45.     {  
  46.         cout << "当前时间: " << w->hour << "心情很好,在看《明朝那些事儿》,收获很大!" << endl;  
  47.     }  
  48. };  
  49.   
  50. class AfternoonState :public State    
  51. {  
  52. public:  
  53.     void writeProgram(Work *w)  
  54.     {  
  55.         if (w->hour < 19)  
  56.         {  
  57.             cout << "当前时间: " << w->hour << "下午午睡后,工作还是精神百倍!" << endl;  
  58.         }  
  59.         else  
  60.         {  
  61.             w->current = new EveningState();  
  62.             w->writeProgram();  
  63.         }  
  64.     }  
  65. };  
  66.   
  67. class ForenonnState :public State  
  68. {  
  69. public:  
  70.     void writeProgram(Work *w)  
  71.     {  
  72.         if (w->hour < 12)  
  73.         {  
  74.             cout << "当前时间: " << w->hour << "上午工作精神百倍!" << endl;  
  75.         }  
  76.         else  
  77.         {  
  78.             w->current = new AfternoonState();  
  79.             w->writeProgram();  
  80.         }  
  81.     }  
  82. };  
  83.   
  84. Work::Work()  
  85. {  
  86.     current = new ForenonnState();  
  87. }  
  88.   
  89.   
  90. int mainD()  
  91. {  
  92.     Work *w = new Work();  
  93.     w->hour = 21;  
  94.     w->writeProgram();  
  95.     cin.get();  
  96.     return 0;  
  97. }  

组合模式

[java]  view plain  copy
  1. #include <iostream>  
  2. #include <vector>  
  3. #include <string>  
  4. using namespace std;  
  5. //合成模式:合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。  
  6. //合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树结构表示出来。  
  7. //合成模式使得客户端把一个个单独的成分对象和由他们复合而成的合成对象同等看待。  
  8. //  
  9. //Mary今天过生日。“我过生日,你要送我一件礼物。”  
  10. //嗯,好吧,去商店,你自己挑。”  
  11. //“这件T恤挺漂亮,买,这条裙子好看,买,这个包也不错,买  
  12. //。”“喂,买了三件了呀,我只答应送一件礼物的哦。  
  13. //”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻烦你包起来。  
  14. //”“……”,MM都会用Composite模式了,你会了没有?  
  15.   
  16. class Component  
  17. {  
  18. public:  
  19.     string name;  
  20.     Component(string name)  
  21.     {  
  22.         this->name = name;  
  23.     }  
  24.     virtual void add(Component *) = 0;  
  25.     virtual void remove(Component *) = 0;  
  26.     virtual void display(int) = 0;  
  27. };  
  28.   
  29. class Leaf :public Component  
  30. {  
  31. public:  
  32.     Leaf(string name) :Component(name)  
  33.     {}  
  34.     void add(Component *c)  
  35.     {  
  36.         cout << "leaf cannot add" << endl;  
  37.     }  
  38.     void remove(Component *c)  
  39.     {  
  40.         cout << "leaf cannot remove" << endl;  
  41.     }  
  42.     void display(int depth)  
  43.     {  
  44.         string str(depth, '-');  
  45.         str += name;  
  46.         cout << str << endl;  
  47.     }  
  48. };  
  49.   
  50. class Composite :public Component  
  51. {  
  52. private:  
  53.     vector<Component*> component;  
  54. public:  
  55.     Composite(string name) :Component(name)  
  56.     {}  
  57.     void add(Component *c)  
  58.     {  
  59.         component.push_back(c);  
  60.     }  
  61.     void remove(Component *c)  
  62.     {  
  63.         vector<Component*>::iterator iter = component.begin();  
  64.         while (iter != component.end())  
  65.         {  
  66.             if (*iter == c)  
  67.             {  
  68.                 component.erase(iter);  
  69.             }  
  70.             iter++;  
  71.         }  
  72.     }  
  73.     void display(int depth)  
  74.     {  
  75.         string str(depth, '-');  
  76.         str += name;  
  77.         cout << str << endl;  
  78.   
  79.         vector<Component*>::iterator iter = component.begin();  
  80.         while (iter != component.end())  
  81.         {  
  82.             (*iter)->display(depth + 2);  
  83.             iter++;  
  84.         }  
  85.     }  
  86. };  
  87.   
  88.   
  89. int main()  
  90. {  
  91.     Component *p = new Composite("小李");  
  92.     p->add(new Leaf("小王"));  
  93.     p->add(new Leaf("小强"));  
  94.   
  95.     Component *sub = new Composite("小虎");  
  96.     sub->add(new Leaf("小王"));  
  97.     sub->add(new Leaf("小明"));  
  98.     sub->add(new Leaf("小柳"));  
  99.   
  100.     p->add(sub);  
  101.     p->display(0);  
  102.   
  103.     cout << "*******" << endl;  
  104.     sub->display(2);  
  105.   
  106.     cin.get();  
  107.   
  108.     return 0;  
  109. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值