Factory Pattern

1.Factory模式两个最重要的功能

(1)定义创建对象的接口,封装了对象的创建。

(2)使得具体化类的工作延迟到了子类中。

2.Factory模式结构示意图

3.实现

 1 #ifndef _PRODUCT_H_
 2 #define _PRODUCT_H_
 3 
 4 class Product
 5 {
 6 public:
 7     virtual ~Product() = 0;
 8 protected:
 9     Product();
10 private:
11 };
12 
13 class ConcreteProduct:public Product
14 {
15 public:
16     ~ConcreteProduct();
17     ConcreteProduct();
18 protected:
19 private:
20 };
21 
22 #endif
Product.h
 1 #include "Product.h"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 Product::Product()
 6 {
 7 
 8 }
 9 Product::~Product()
10 {
11 
12 }
13 
14 ConcreteProduct::ConcreteProduct()
15 {
16     cout<<"ConcreteProduct..."<<endl;
17 }
18 ConcreteProduct::~ConcreteProduct()
19 {
20 
21 }
Product.cpp
 1 #ifndef _FACTORY_H_
 2 #define _FACTORY_H_
 3 
 4 class Product;
 5 
 6 class Factory
 7 {
 8 public:
 9     virtual ~Factory() = 0;
10     virtual Product* CreateProduct() = 0;
11 protected:
12     Factory();
13 private:
14 };
15 
16 class ConcreteFactory:public Factory
17 {
18 public:
19     ~ConcreteFactory();
20     ConcreteFactory();
21     Product* CreateProduct();
22 protected:
23 private:
24 };
25 #endif
Factory.h
 1 #include "Factory.h"
 2 #include "Product.h"
 3 
 4 #include <iostream>
 5 using namespace std;
 6 
 7 Factory::Factory()
 8 {
 9 
10 }
11 Factory::~Factory()
12 {
13 
14 }
15 ConcreteFactory::ConcreteFactory()
16 {
17     cout<<"ConcreteFactory....."<<endl;
18 }
19 ConcreteFactory::~ConcreteFactory()
20 {
21 
22 }
23 Product* ConcreteFactory::CreateProduct()
24 {
25     return new ConcreteProduct();
26 }
Factory.cpp
原文地址:https://www.cnblogs.com/programmer-wfq/p/4651339.html