讀《大話設計模式》---工廠方法模式(factory method)

工廠方法模式(factory method) :

定義一個用於創建對象的接口,讓子類決定實例化哪一個類。工廠方法使一個類的實例化延遲到他的子類。

 

簡單工廠模式和工廠方法模式的區別:

1.簡單工廠模式

簡單工廠模式的最大優點在於工廠類中包含了必要的邏輯判斷,根據客戶端的選擇條件動態實例化相關的類,對於客戶端來說,去除了與具體產品的依賴。

2.工廠方法模式

工廠方法模式實現時,客戶需要決定實例化哪一個工廠來決定產品類,判斷選擇的問題還是存在的,也就是說:工廠方法把簡單工廠的內部邏輯判斷移到了客戶端代碼來實現。你想要加功能,本來是修改工廠類的,而現在是修改客戶端。

 

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

//定義工廠方法所創建的對象的接口 class Product { public:      void performance(); }; //具體的產品,實現Product接口 class ConcreteProduct : public Product { public: } //聲明工廠方法,該方法返回一個Product類型的對象 class Creator { public:       virtural  Product * Create() = 0;  } //重定義工廠方法以返回一個ConcreteProduct實例 class ConcreteCreator : public Creator { public:       Product * Create()      {               return new ConcreteProduct();      } }

一個具體的工廠方法模式的實例:

  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. }
發佈了107 篇原創文章 · 獲贊 12 · 訪問量 60萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章