Details of C++ design mode Static Factory

  • 2020-06-07 04:56:28
  • OfStack

The simple factory pattern is not one of the 23 design patterns proposed by GOF. The factory pattern has a very graphic description. The class that builds the object is like a factory, and the object that needs to be built is a product.

Applicable occasions

1. In the program, a large number of objects need to be created, which results in many and miscellaneous new operations of objects, and the simple factory mode needs to be used;
2. Since the creation process of the object is what we don't need to care about, but what we focus on is the actual operation of the object, we need to separate the creation and operation of the object, so as to facilitate the later expansion and maintenance of the program.

1. Define abstract classes, which are interfaces


class Product
{
public:
 virtual void show()=0;
};

2. The definition requires concrete implementation classes, inherits abstract classes, and assumes three products


class ProductA:public Product
{
public:
 virtual void show()
 {
 printf("ProductA\n");
 }
};
 
class ProductB:public Product
{
public:
 virtual void show()
 {
 printf("ProductB\n");
 }
};
 
class ProductC:public Product
{
public:
 virtual void show()
 {
 printf("ProductC\n");
 }
};

3. Define the factory class, which is responsible for producing the product, and pass in the specific parameters to decide which product to produce


class Factory
{
public:
 Product* CreateProduct(int num)
 {
 switch(num)  // Instantiate an object by passing arguments 
 {
 case 1:
  return new ProductA();
  break;
 case 2:
  return new ProductB();
  break;
 case 3:
  return new ProductC();
  break;
 default:
  return NULL;
  break;
 }
 }
};

4. Actual invocation


int main()
{
 Factory* ProductFactory=new Factory();    // First of all have 1 Five factory objects 
 Product* A=ProductFactory->CreateProduct(1); // Use polymorphism and factory object to pass reference to decide which product to produce 
 A->show();
 Product* B=ProductFactory->CreateProduct(2);
 B->show();
 Product* C=ProductFactory->CreateProduct(3);
 C->show();
}

Related articles: