读《大话设计模式》---工厂方法模式(factory method)

来源:互联网 发布:南京知臣服饰 编辑:程序博客网 时间:2024/05/29 15:17

工厂方法模式(factory method) :

定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到他的子类。

 

简单工厂模式和工厂方法模式的区别:

1.简单工厂模式

简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。

2.工厂方法模式

工厂方法模式实现时,客户需要决定实例化哪一个工厂来决定产品类,判断选择的问题还是存在的,也就是说:工厂方法把简单工厂的内部逻辑判断移到了客户端代码来实现。你想要加功能,本来是修改工厂类的,而现在是修改客户端。

 

工厂方法模式的一般形式:

  1. //定义工厂方法所创建的对象的接口
  2. class Product
  3. {
  4. public:
  5.      void performance();
  6. };
  7. //具体的产品,实现Product接口
  8. class ConcreteProduct : public Product
  9. {
  10. public:
  11. }
  12. //声明工厂方法,该方法返回一个Product类型的对象
  13. class Creator
  14. {
  15. public:
  16.       virtural  Product * Create() = 0; 
  17. }
  18. //重定义工厂方法以返回一个ConcreteProduct实例
  19. class ConcreteCreator : public Creator
  20. {
  21. public:
  22.       Product * Create()
  23.      {
  24.               return new ConcreteProduct();
  25.      }
  26. }

一个具体的工厂方法模式的实例:

  1. #include <iostream>
  2. using namespace std;
  3. //志愿者
  4. class volunteer
  5. {
  6. public:
  7.     void regular()
  8.     {
  9.         cout << "维持秩序" << endl;
  10.     }
  11.     void guid()
  12.     {
  13.         cout << "向导" << endl;
  14.     }
  15.     void help()
  16.     {
  17.         cout << "助人为乐" << endl;
  18.     }
  19. };
  20. //大学生志愿者
  21. class undergraduate : public volunteer
  22. {
  23. };
  24. //社会志愿者
  25. class society : public volunteer
  26. {
  27.     
  28. };
  29. //抽象工厂(用来生产志愿者,虽然听起来很别扭,呵呵)
  30. class factory
  31. {
  32. public:
  33.     virtual volunteer * CreateVolunteer() = 0;
  34. };
  35. //具体工厂(用来生产大学生志愿者)
  36. class undergraduatefactory : public factory
  37. {
  38. public:
  39.     volunteer * CreateVolunteer()
  40.     {
  41.         cout << "创建大学生志愿者:" << endl; 
  42.         return new undergraduate();
  43.     }
  44. };
  45. //具体工厂(用来生产社会志愿者)
  46. class societyfactory : public factory
  47. {
  48. public:
  49.     volunteer * CreateVolunteer()
  50.     {
  51.         cout << "创建社会志愿者:" << endl; 
  52.         return new society();
  53.     }
  54. };
  55. int main()
  56. {
  57.     factory * _afactory = new undergraduatefactory();
  58.     volunteer * _avolunteer = _afactory->CreateVolunteer();
  59.     _avolunteer->guid();
  60.     factory * _bfactory = new societyfactory();
  61.     volunteer * _bvolunteer = _bfactory->CreateVolunteer();
  62.     _bvolunteer->regular();
  63.     return 0;
  64. }
原创粉丝点击