C++设计模式中的工厂模式详细介绍

  ```cpp

  #include

  using namespace std;

  class Product

  {

  public:

  ~Product() {}

  // 纯虚函数

  virtual void Create(string content) = 0;

  };

  class ProductA : public Product

  {

  public:

  void Create(string content) override {

  cout << "ProductA " << content << endl;

  }

  };

  class ProductB : public Product

  {

  public:

  void Create(string content) override {

  cout << "ProductB " << content << endl;

  }

  };

  class Factory

  {

  public:

  virtual Product* CreateProductA() = 0;

  virtual Product* CreateProductB() = 0;

  Product* m_pProductA;

  Product* m_pProductB;

  virtual ~Factory() {

  if (m_pProductA)

  delete m_pProduct;

  if(m_pProductB)

  delete m_pProductB;

  }

  };

  class FactorySubOne : public Factory

  {

  public:

  virtual Product* CreateProductA() override{

  return m_pProductA = new ProductA();

  }

  virtual Product* CreateProductB() override {

  return m_pProductB = new ProductB();

  }

  };

  class FactorySubTwo : public Factory

  {

  public:

  virtual Product* CreateProductA() override{

  return m_pProductA = new ProductA();

  }

  virtual Product* CreateProductB() override {

  return m_pProductB = new ProductB();

  }

  };

  int main()

  {

  FactorySubOne factroy_sub_one;

  FactorySubTwo factroy_sub_two;

  factroy_sub_one.CreateProductA()->Create("FactorySubOne A");

  factroy_sub_one.CreateProductB()->Create("FactorySubOne B");

  factroy_sub_two.CreateProductA()->Create("FactorySubTwo A");

  factroy_sub_two.CreateProductB()->Create("FactorySubTwo B");

  system("pause");

  }