C + + implementation factory mode

1, Simple factory mode

1.1 simple factory mode

Simple Factory Pattern specifically defines a class to be responsible for creating instances of other classes. The created instances usually have a common parent class.

Simple factory mode is a way to instantiate objects. As long as you enter the name of the object to be instantiated, you can create the object you need through the corresponding factory function of the factory object.

1.2 role of simple factory model

(1) Factory role (factory class):

The factory role, that is, the factory class, is the core of the simple factory pattern. It is responsible for creating the internal logic of all instances. The factory class can be directly called by the outside world to create the required product objects.

(2) Product abstract product role:

The abstract product role is the parent class of all objects created by the simple factory pattern and is responsible for describing the announcement interface common to all instances. The specific product objects created are all subclass objects.

(3) ConcreteProduct specific product roles:

The specific product role is the creation goal of the simple factory pattern. Each concrete product role inherits the abstract product role and needs to implement the methods defined in the abstract product.

ProductA, ProductB and ProductC inherit from the Product virtual class, and the Show method is the self description of different products; Factory depends on ProductA, ProductB and ProductC. Factory creates different Product objects according to different conditions

1.3 application of simple factory mode

In the program, when there are many objects to be created, resulting in many and miscellaneous new operations of objects, the simple factory mode needs to be used;
Because we don't need to care about the object creation process, but we pay attention to the actual operation of the object, we need to separate the object creation and operation, so as to facilitate the later program expansion and maintenance.

1.4 advantages and disadvantages of simple factory mode

Disadvantages:

  • Simple factory mode will increase the number of system classes, and increase the complexity and understanding difficulty of the system to a certain extent;
  • It is difficult to expand the system. Once new products are added, the factory logic needs to be modified, which is not conducive to system expansion and maintenance; In the simple factory mode, all products are created by the same factory. The factory class has heavy responsibilities and complex business logic. The coupling between specific products and factory classes is high, which seriously affects the flexibility and scalability of the system.

1.5 implementation of simple factory mode

A TV factory manufactures TV sets for various brands, which can be realized by using the model of simple factory.

#include <iostream>
#include <vector>
using namespace std;
  
typedef enum ProductTypeTag
{
  Hair,
  Hisense,
}PRODUCTTYPE;
  
//Abstract product TV (TV)
class TV
{
public:
  virtual void Show() = 0;
};
 //Specific product category: hairtv (Haier TV)
class HairTV : public TV
public:
  void Show()
  {
    cout<<"I'm HairTV "<<endl;
  }
};
 //Specific product category hisensetv (Hisense TV)  
class  HisenseTV : public TV
{
public:
  void Show()
  {
    cout<<"I'm HisenseTV"<<endl;
  }
};
  

// Factory tvfactory (TV factory)
class TVFactory
{
public:
  TV* CreateTV(PRODUCTTYPE type)
  {
    switch (type)
    {
    case Hair:
      return new HairTV();
  
    case Hisense:
      return new HisenseTV();
    default:
      return NULL;
    }
  }
};
  
int main(int argc, char *argv[])
{
  // Create factory class object
  TVFactory *myTVFactory = new  TVFactory();
  TV *hairTV = myTVFactory->CreateTV(Hair);
  if (hairTV != NULL)
    hairTV->Show();
  
  TV *hisenseTV = myTVFactory->CreateTV(Hisense);
  if (hisenseTV != NULL)
    hisenseTv->Show();
  
  delete  TVFactory;
   TVFactory = NULL;
  
  delete hairTV;
  hairTV = NULL;
  
  delete hisenseTV;
  hisenseTV = NULL;    
  
  return 0;
}

TVFactory is a factory class, which is the core of the whole system. It provides a static factory method CreateTV (), which contains a string type parameter. In the internal business logic, different specific product classes are instantiated according to the parameter values to return dependent objects.

2, Factory method model

2.1 introduction to plant method

The biggest disadvantage of the simple factory mode is that when new products are added to the system, the factory class must be modified and necessary processing logic must be added, which violates the "opening and closing principle".

Factory method pattern definition: in the factory pattern, the factory parent class is responsible for defining the announcement interface for creating product objects, while the factory subclass is responsible for generating specific product objects. The purpose is to delay the instantiation of products to the factory subclass, and determine which specific product class should be instantiated through the factory subclass.

2.2 mode structure

(1) Product

Abstract product is the interface that defines the product. It is not only the supertype of the object created by the factory method pattern, but also the common parent class or interface of the product object.

(2) ConcreteProduct (specific product)

Concrete products implement the interface of abstract products, and some types of concrete products are created by special concrete factories.

(3) Factory (Abstract Factory)

(4) ConcreteFactory (specific factory)

The concrete factory is a subclass of the abstract factory class. It implements the factory methods defined in the abstract factory and can be called by customers to return an instance of a concrete product class.

2.3 Application

The meaning of factory method pattern is to define a factory interface for creating product objects and postpone the actual creation to subclasses. The core factory class is no longer responsible for the creation of products. In this way, the core class becomes an abstract factory role and is only responsible for the interfaces that must be implemented by specific factory subclasses. The advantage of further abstraction is that the factory method pattern enables the system to introduce new products without modifying specific factory roles.

1. In the early stage of design, considering that the product will be expanded in the later stage, the factory method mode can be used;

2. When the product structure is complex, the factory method mode can be used;

                                                                                                                                                        

2.4 advantages and disadvantages

Advantages: the system has good expansibility and conforms to the "opening and closing principle". When the system adds a new product, there is no need to modify the interface provided by the abstract factory and the abstract product, the client, or other specific factories and specific products, but just add a specific factory and specific product.

Disadvantages: when adding new products, you need to write new specific product classes and provide corresponding specific factory classes. The number of classes in the system will increase in pairs, which increases the complexity of the system to a certain extent.

2.5 examples

In the simple factory mode, TV sets are produced through a TV generation factory. When new brand TV sets need to be added, the factory method in the factory class has to be repaired, which violates the "opening and closing principle".

The factory method mode divides the original factory and provides a sub factory for each brand of TV. Haier factory is responsible for producing Haier TV and Hisense factory is responsible for producing Hisense TV. If TCL TV is added, only a new TCL factory needs to be added.

#include <iostream>
using namespace std;
 /*Abstract product TV (TV)*/ 
class TV
{
public:
  virtual void Show() = 0;
};
 /*Specific product category: hairtv (Haier TV)*/ 
class HairTV : public TV
{
public:
  void Show()
  {
    cout<< "I'm HairTV"<<endl;
  }
};
/*Specific product category hisensetv (Hisense TV)*/
class HisenseTV : public TV
{
public:
  void Show()
  {
    cout<< "I'm HisenseTV"<<endl;
  }
};
/*Factory (TV factory)*/  
class TVFactory
{
public:
  virtual TV *CreateTV() = 0;
};
 /*Specific factory: hairtvfactory (Haier TV factory)*/ 
class HairTVFactory : public TVFactory
{
public:
  TV *CreateTV()
  {
    return new HairTV ();
  }
};
 /*Specific factory type hisensetv (Hisense TV factory type)*/ 
class HisenseTVFactory : public TVFactory
{
public:
  TV *CreateTV()
  {
    return new HisenseTV ();
  }
};
  
int main(int argc , char *argv [])
{
  TVFactory *hairTVFactory = new HairTVFactory();
  TV *hairTV = hairTVFactory->CreateTV();
  hairTV->Show();
  
  TVFactory *hisenseTVFactory = new HisenseTVFactory();
  TV *hisenseTV = hisenseTVFactory->CreateTV();
  hisenseTV->Show();
  
  if (hairTVFactory!= NULL)
  {
    delete hairTVFactory;
    hairTVFactory = NULL;
  }
  
  if (hairTV != NULL)
  {
    delete hairTV;
    hairTV = NULL;
  }
  
  if (hisenseTVFactory != NULL)
  {
    delete hisenseTVFactory;
    hisenseTVFactory = NULL;
  }
  
  if (hisenseTV != NULL)
  {
    delete hisenseTV;
    hisenseTV = NULL;
  }
  return 0;
}

3, Abstract factory pattern

3.1 abstract factory model

Abstract factory pattern is a generalized version of factory method pattern. Factory pattern is a special abstract factory pattern. In factory pattern, each specific factory can only produce one specific product, while in abstract factory method pattern, a specific factory can produce multiple specific products.

3.2 model role

Product hierarchy and product family:

Product hierarchy:

(1) AbstractFactory

Abstract factory is used to declare the methods to generate abstract products. A group of methods can be defined in an abstract factory, and each method corresponds to a product hierarchy.

(2) ConcreteFactory (specific factory)

The concrete factory implements the method of abstract products declared by the abstract factory to generate a set of concrete products

(3) AbstractProduct (abstract product)

Abstract products declare interfaces for each product, and the abstract business methods of the product are defined in the abstract product.

(4) ConcreteProdunct (specific product)

A specific product defines a specific product object produced by a specific factory and implements the business methods defined in the abstract product interface.

3.3 application

When the object to be created is a series of interrelated or interdependent product families, you can use the abstract factory pattern. To put it more clearly, in an inheritance system, If there are multiple hierarchies (that is, there are multiple abstract classes) and there are certain associations or constraints between the implementation classes in each hierarchy, the abstract factory pattern can be used. If there are no associations or constraints between the implementation classes in each hierarchy, it is more appropriate to use multiple independent factories to create products.

  1. It is suitable for places where products are interrelated, interdependent and constrained
  2. Where product families need to be dynamically switched

3.4 advantages and disadvantages

advantage:

  1. Abstract factory pattern puts the dependency and constraint relationship of product family into abstract factory for easy management.
  2. Responsibilities are decoupled. Users don't need to care about a bunch of details they don't care about. The abstract factory is responsible for the creation of components
  3. It is easy to switch product families. You only need to add a specific factory implementation, and the client can choose another package

Disadvantages:

  1. Abstract factory pattern classes are increasing rapidly. A product family needs to add a specific factory implementation, which is cumbersome
  2. Product families are difficult to expand. When a product is added to the product family, a function needs to be added to the abstract factory interface, and all corresponding specific factory implementations need to be modified, which is seriously enlarged.
  3. The abstract factory does not completely mask the creation details, but gives components. In this case, it can be used in combination with factory mode or simple factory mode.

3.5 examples

For example, an electrical factory can produce various types of electrical appliances, such as Haier factory can produce Haier TV and Haier air conditioner, and TCL factory can produce TCL TV and TCL air conditioner. Electrical appliances of the same brand constitute a product family, while electrical appliances of the same type constitute a product hierarchy.

#include <iostream>
using namespace std;
  
// Abstract product class television (television)
class Television
{
public:
  virtual void Show() = 0;
};
  
//Specific product category HaierTelevision (Haier TV)
class HaierTelevision : public Television
{
public:
  void Show()
  {
    cout<<"I'm HaierTelevision"<<endl;
  }
};
 //Specific product category: TCL television
class TCLTelevision : public Television
{
public:
  void Show()
  {
    cout<<"I'm TCLTelevision"<<endl;
  }
};
  
// Abstract product class AirCondition (air conditioning class)
class AirCondition
{
public:
  virtual void Show() = 0;
};
//Specific product category: hairaircondition (Haier air conditioner)
class HairAirCondition : public AirCondition
{
public:
  void Show()
  {
    cout<<"I'm HairAirCondition"<<endl;
  }
};
 //Specific product category: TCLAirCondition(TCL air conditioner)
class TCLAirCondition : public AirCondition
{
public:
  void Show()
  {
    cout<<"I'm TCLAirCondition"<<endl;
  }
};
  
// Abstract factory class effactory (electrical factory class)
class EFactory
{
public:
  virtual Television *CreateTelevision() = 0;
  virtual AirCondition *CreateAirCondition() = 0;
};
 //Specific factory: hairfactory (Haier factory)
class HairFactory : public EFactory
{
public:
  HaierTelevision *CreateHaierTelevision()
  {
    return new HaierTelevision();
  }
  
  AirCondition *CreateAirCondition()
  {
    return new AirCondition();
  }
};
 //Specific factory class TCLFactory(TCL factory class) 
class TCLTelevision : public EFactory
{
  ProductA *CreateTCLTelevision()
  {
    return new TCLTelevision();
  }
  
  ProductB *CreateTCLAirCondition()
  {
    return new TCLAirCondition();
  }
};
  
int main(int argc, char *argv[])
{
  EFactory *hairFactory = new HairFactory ();/*Instance chemical plant abstract class*/
  Television *haierTelevision =hairFactory->CreateTelevision();/*Instantiate product abstract class*/
  AirCondition *haierAirCondition = hairFactory->CreateAirCondition();
  
  haierTelevision->Show();
  haierAirCondition->Show();
  
  EFactory *tCLFactory = new TCLFactory ();
  Television *tCLTelevision = tCLFactory->CreateTelevision();
  AirCondition *tCLAirCondition = tCLFactory->CreateAirCondition();
  
  tCLTelevision->Show();
  tCLAirCondition->Show();
  
  if (hairFactory != NULL)
  {
    delete hairFactory;
    hairFactory = NULL;
  }
  
  if (haierTelevision != NULL)
  {
    delete haierTelevision;
    haierTelevision= NULL;
  }
  
  if (tCLAirCondition != NULL)
  {
    delete tCLAirCondition;
    tCLAirCondition = NULL;
  }
  
  if (tCLFactory != NULL)
  {
    delete tCLFactory;
    tCLFactory= NULL;
  }
  
  if (tCLTelevision != NULL)
  {
    delete tCLTelevision;
    tCLTelevision = NULL;
  }
  
  if (tCLAirCondition != NULL)
  {
    delete tCLAirCondition;
    tCLAirCondition = NULL;
  }
}

4, Summary

  1. You should have found that if there is only one component in the abstract factory mode, it actually degenerates to the factory method mode, that is, there is no concept of product family, and there is only one product left. Therefore, there is an internal relationship among simple factory, factory method and abstract factory, and the difference is only the complexity of the product.
  2. The essence of abstract factory is to select product family, so we can identify whether abstract factory can be applied according to this feature.

reference:

[1]Factory mode (C + + implementation): https://www.cnblogs.com/huiz/p/8232783.html

[2] Simple factory of design mode, factory method mode (c + +): https://blog.csdn.net/u012219045/article/details/60467306

[3]The design pattern of C + + implementation -- simple factory pattern: https://www.cnblogs.com/jostree/p/4251756.html

[4] Simple factory pattern example of C + + design pattern: https://www.jb51.net/article/55858.htm

[5] Factory method pattern of C + + design pattern: https://www.jb51.net/article/55860.htm

[6] Abstract factory pattern of C + + design pattern: https://www.jb51.net/article/55861.htm

[7] The difference between abstract factory mode and factory mode: https://www.zhihu.com/question/20367734

[8] Abstract factory pattern application scenarios (advantages and disadvantages of 24 design patterns): https://www.haitaoseo.com/960718.html

Keywords: C++ Design Pattern

Added by david212 on Tue, 21 Dec 2021 12:16:01 +0200