C++ implementation of simple factory pattern and personal understanding

table of Contents

Preface

Simple factory pattern

Mode definition

C++ implementation method

Pros and cons of the model

Application scenarios

Common specific applications of simple factory mode

expand


Preface

Design Pattern (Design Pattern) is a set of code design experience that is used repeatedly, known to most people, classified and cataloged, and the purpose of using Design Pattern is to improve the readability, maintainability and reliability of the code.

This article is about the author's doubts about the simple factory model, factory method model and abstract factory model while studying the "Design Patterns" course. After consulting the blogs of the predecessors, I would like to share my personal understanding and consolidate the learning results, if any Error, please leave a message to point out.

This article mainly discusses the simple factory pattern based on the following aspects:

  • Mode definition
  • C++ implementation method
  • Pros and cons of the model
  • Application scenarios
  • Common specific applications of simple factory mode
  • expand

Simple factory pattern

Before learning the simple factory model, we need to understand the three concepts of "abstract product category", "concrete product category", and "factory category" . Since these three models all contain the keyword "factory", it means that these design patterns are abstracted from the design ideas of factories, so we will map these concepts to factories in real life.

Specific product category:  It is the creation target of the simple factory pattern, and all created objects act as instances of a specific category of this role. Each concrete product role inherits the abstract product role and needs to implement the abstract methods declared in the abstract product.

Abstract product class:  It is the parent class of all objects created by the factory class, and encapsulates the public methods of various product objects. Its introduction will improve the flexibility of the system, so that only a common factory method needs to be defined in the factory class , Because all specific product objects created are subclass objects.

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

For example, take mobile phones as an example. Phone is an abstract product category of all mobile phones of different brands. It contains the common features of all mobile phones-being able to make calls and surf the Internet, etc.; and such as Huawe iPhone and Xiaomi mobile phones ( XiaomiPhone) are the specific product categories of mobile phones, which encapsulate their different functions and structures. The mobile phone's OEM factory "Foxconn (Foxconn)" is a factory that produces mobile phones, and completes various brands according to different design plans and needs. The specific assembly task of the mobile phone; finally sold to us these "clients" through various channels for use.

 

Mode definition

Define a factory class, which can return instances of different specific product classes according to different parameters. The created instances usually have a common parent class (abstract product class).

C++ implementation method

The simple factory model can be divided into ordinary simple factory, multi-method simple factory, and static method simple factory.

We will use a mobile phone as a product to demonstrate the realization of a simple factory:

(1) Ordinary simple factory:

#include <iostream>

using namespace std;

enum PhoneType
{
    Huawei = 1;
    Xiaomi;
};


//手机的抽象产品类
class Phone
{
public:
    virtual void getPhone() = 0; //为具体产品类提供公共接口
    virtual ~Phone(){}
};

//具体产品类:华为手机类
class HuaweiPhone:public Phone
{
public:
    virtual void getPhone()
    {
        cout<<"华为手机"<<endl;
    }
};

//具体产品类:小米手机类
class XiaomiPhone:public Phone
{
public:
    virtual void getPhone()
    {
        cout<<"小米手机"<<endl;
    }
};

//工厂类
class PhoneFactory
{
public:
    virtual Phone* creatPhone(int phonetype)
    {
        Phone *m_phone = NULL;
        switch(phonetype)
        {
        case 1:
            m_phone = new HuaweiPhone(); break;
        case 2:
            m_phone = new XiaomiPhone(); break;
        default:
            break;
        }
        return m_phone;
    }
};

//客户端
int main()
{
    int i = 0;
    PhoneFactory *factory = new PhoneFactory();
    Phone *myphone = NULL;

    cout<<"输入你想要的手机(1/2):"<<endl;
    cin>>i;
    
    //根据需求生产想要的产品
    myphone = factory->creatPhone(i);
    myphone->getPhone();

    delete myphone;
    delete factory;

    system("pause");
    return 0;
}

(2) Multi-method simple factory

The multi-method simple factory is an improvement to the ordinary factory model. In the ordinary factory model, if the passed parameter type is wrong, the object cannot be created correctly. The multi-method simple factory model provides multiple factory methods to create different product classes. Object.

//工厂类
class PhoneFactory
{
public:
    //华为手机的生成方法
    virtual Phone* getHuawei()
    {
        return new HuaweiPhone();
    }
    //小米手机的生成方法
    virtual Phone* getXiaomi()
    {
        return new XiaomiPhone();
    }

}

//客户端
int main()
{
    int i = 0;
    PhoneFactory *factory = new PhoneFactory();
    Phone *myphone = NULL;

    cout<<"输入你想要的手机(1/2):"<<endl;
    cin>>i;
    
    //根据需求生产想要的产品    
    if(i == 1){
        myphone = factory->getHuawei();
    }
    else{
        myphone = factory->getXiaomi();
    }
    
    myphone->getPhone();

    delete myphone;
    delete factory;

    system("pause");
    return 0;
}

(3) Simple factory with static method

Set the factory method to static, so that you can directly call the static factory method without creating a factory object.

//工厂类
class PhoneFactory
{
public:
    //静态工厂方法
    static Phone* creatPhone(int phonetype)
    {
        Phone *m_phone = NULL;
        switch(phonetype)
        {
        case 1:
            m_phone = new HuaweiPhone(); break;
        case 2:
            m_phone = new XiaomiPhone(); break;
        default:
            break;
        }
        return m_phone;
    }
};

//客户端
int main()
{
    int i = 0;
    Phone *myphone = NULL;

    cout<<"输入你想要的手机(1/2):"<<endl;
    cin>>i;
    
    //根据需求生产想要的产品
    myphone = PhoneFactory::creatPhone(i);
    myphone->getPhone();

    delete myphone;

    system("pause");
    return 0;
}

 

Pros and cons of the model

The main advantages are:

  • The factory class contains the necessary judgment logic, which can decide when to create an instance of the product class. The client can be exempted from the responsibility of directly creating product objects and only "consuming" products . The simple factory model realizes the separation of object creation and use. .
  • The client does not need to know the category name of the specific product category created , only the parameters corresponding to the specific product category. For some complex category names, the simple factory model can reduce the user's memory to a certain extent .
  • By introducing configuration files, new specific product categories can be replaced and added without modifying any client code, which improves the flexibility of the system to a certain extent.

The main disadvantages are:

  • Since the factory class concentrates the creation logic of all products, and the responsibilities are too heavy , once it fails to work normally, the entire system will be affected.
  • Using the simple factory model will inevitably increase the number of classes in the system (introducing new factory classes) and increase the complexity and difficulty of understanding the system.
  • System expansion is difficult. Once a new product is added, the factory logic has to be modified. When there are many product types, the factory logic may be too complicated, which is not conducive to system expansion and maintenance, and violates the principle of opening and closing .
  • The static simple factory model uses a static factory method, which prevents the factory role from forming a hierarchy based on inheritance.

Application scenarios

  • The factory class is responsible for creating fewer objects . Since there are fewer objects created, the business logic in the factory method will not be too complicated.
  • The client only knows the parameters passed to the factory class, and does not care about how to create the object.

Common specific applications of simple factory mode

  • Usually when using word office software, pie charts, bar charts, line charts and other graphics will be drawn as needed. A factory class can be provided to create different types of graphics according to the user's choice.
  • QQ space background style, blog background style, etc. provide various styles of styles. Provide a factory to create different background styles according to the specific styles selected by the user to decorate the QQ space.
  • Cinema discount algorithm: discount algorithm such as VIP 50%, student ticket 50%, adult ticket normal charge, etc.

expand

(1) Why do we need a simple factory model and what are its benefits?

Answer: If you do not use the simple factory pattern, we need to create objects in the client code. When multiple similar objects need to be created, the readability of our client code will be reduced. After all, the client code will not be like ours. The example here is just as simple. Using the simple factory model, the task of generating objects is handed over to the factory, and the client only needs to "consume" the objects.

When we need to expand the product category, we only need to find the product category file, add the specific product category needed, then add the corresponding "generated object" code in the factory category, and finally add the "consumer object" code in the client Code", this completes the originally troublesome expansion task.

The simple factory pattern is a pattern that does not fully comply with the "opening and closing principle". When there is a new specific product class, it is necessary to modify the method of generating objects in the factory class. The multi-method simple factory model has improved this shortcoming. Different objects have different generation methods, and the judgment of what kind of object originally needed to be generated in the method of generating the object is handed over to the client to complete.

The benefits of the factory model can refer to this blog "The Benefits of the Factory Model of Design Patterns" .

(2) Can the simple factory pattern only be used to create objects?

Answer: In fact, the simple factory pattern can be applied flexibly, please refer to this blog "C++ Work Notes-Basics of Simple Factory Pattern" .

 

Guess you like

Origin blog.csdn.net/gaggagaasd/article/details/107623949