Creational design patterns: 2. Simple factory pattern, factory pattern, abstract factory pattern

Table of contents

1. Simple working mode

2. Factory mode

3. Abstract factory pattern

4. The relationship between simple factory pattern, factory pattern and abstract factory pattern

1. Simple factory mode and factory mode

2. Abstract factory pattern and factory pattern


I mainly feel that these modes are relatively similar, so I will explain them together, which is also convenient for learning and distinguishing.

1. Simple working mode

1. Meaning: The simple factory pattern is a creational design pattern that provides a unified interface to create different types of objects without directly exposing the object creation logic. This can reduce the coupling degree of the system and increase the flexibility and maintainability of the code.

2. An example of C++ implementing a simple factory pattern:

#include <iostream>

// 抽象产品类
class Product {
public:
    virtual void operation() = 0;
};

// 具体产品类A
class ConcreteProductA : public Product {
public:
    void operation() override {
        std::cout << "Product A operation" << std::endl;
    }
};

// 具体产品类B
class ConcreteProductB : public Product {
public:
    void operation() override {
        std::cout << "Product B operation" << std::endl;
    }
};

// 简单工厂类
class SimpleFactory {
public:
    // 根据类型创建产品对象
    static Product* createProduct(const std::string& type) {
        if (type == "A") {
            return new ConcreteProductA();
        } else if (type == "B") {
            return new ConcreteProductB();
        } else {
            return nullptr;
        }
    }
};

int main() {
    // 创建产品A
    Product* productA = SimpleFactory::createProduct("A");
    productA->operation();

    // 创建产品B
    Product* productB = SimpleFactory::createProduct("B");
    productB->operation();

    delete productA;
    delete productB;

    return 0;
}

In the example above, the abstract product class Productdefines the interface common to all concrete product classes. The concrete product class ConcreteProductAand ConcreteProductBis the implementation of the concrete product.

The simple factory class SimpleFactoryis responsible for creating corresponding product objects according to different types. In createProductthe method, according to the type parameter passed in, the corresponding product object is returned.

In mainthe function, SimpleFactory::createProductdifferent types of product objects are created by calling methods, and their operationmethods are called for operations.

Run the program, the output is:

Product A operation
Product B operation

This shows that the simple factory pattern successfully encapsulates the creation logic of objects, and can create corresponding objects according to different types.

2. Factory mode

1. Meaning: Factory Pattern (Factory Pattern) is a creational design pattern that provides the best way to create objects by encapsulating the code for creating objects in a factory class rather than in client code Instantiate the object directly.

2. Example of factory pattern implemented by C++:

#include <iostream>
#include <string>

// 抽象产品类
class Product {
public:
    virtual ~Product() {}
    virtual std::string operation() const = 0;
};

// 具体产品类A
class ConcreteProductA : public Product {
public:
    std::string operation() const override {
        return "ConcreteProductA";
    }
};

// 具体产品类B
class ConcreteProductB : public Product {
public:
    std::string operation() const override {
        return "ConcreteProductB";
    }
};

// 抽象工厂类
class Factory {
public:
    virtual ~Factory() {}
    virtual Product* createProduct() const = 0;
};

// 具体工厂类A
class ConcreteFactoryA : public Factory {
public:
    Product* createProduct() const override {
        return new ConcreteProductA();
    }
};

// 具体工厂类B
class ConcreteFactoryB : public Factory {
public:
    Product* createProduct() const override {
        return new ConcreteProductB();
    }
};

int main() {
    // 使用工厂A创建产品A
    Factory* factoryA = new ConcreteFactoryA();
    Product* productA = factoryA->createProduct();
    std::cout << productA->operation() << std::endl;

    // 使用工厂B创建产品B
    Factory* factoryB = new ConcreteFactoryB();
    Product* productB = factoryB->createProduct();
    std::cout << productB->operation() << std::endl;

    delete factoryA;
    delete productA;
    delete factoryB;
    delete productB;

    return 0;
}

In the above example, the abstract product class Productdefines the interface of the product, ConcreteProductAand the concrete product class ConcreteProductBimplements the concrete product.

The abstract factory class Factorydefines the interface for creating products, ConcreteFactoryAand the concrete factory class ConcreteFactoryBimplements the concrete factory.

In client code, we can use different factories to create different products. Through the factory mode, the client code is decoupled from the implementation of specific products, thereby improving the maintainability and scalability of the code.

3. Abstract factory pattern

1. Meaning: Abstract Factory Pattern (Abstract Factory Pattern) is to create other factories around a super factory. The super factory is also known as the factory of other factories. This type of design pattern is a creational pattern, which provides an optimal way to create objects.

In the Abstract Factory pattern, interfaces are factories responsible for creating a related object without specifying their class explicitly. Each generated factory can provide objects according to the factory pattern.

The abstract factory pattern provides an interface for creating a series of related or interdependent objects without specifying a concrete implementation class. By using the abstract factory pattern, the client can be decoupled from the creation process of specific products, so that the client can create a family of products through the factory interface.

2. Example of factory pattern implemented by C++:


#include <iostream>

// 抽象产品A

class AbstractProductA {
public:
    virtual void operationA() = 0;
};

// 具体产品A1

class ConcreteProductA1 : public AbstractProductA {
public:
    void operationA() override {
        std::cout << "ConcreteProductA1::operationA()" << std::endl;
    }
};

// 具体产品A2

class ConcreteProductA2 : public AbstractProductA {
public:
    void operationA() override {
        std::cout << "ConcreteProductA2::operationA()" << std::endl;
    }
};

// 抽象产品B

class AbstractProductB {
public:
    virtual void operationB() = 0;
};

// 具体产品B1

class ConcreteProductB1 : public AbstractProductB {
public:
    void operationB() override {
        std::cout << "ConcreteProductB1::operationB()" << std::endl;
    }
};

// 具体产品B2

class ConcreteProductB2 : public AbstractProductB {
public:
    void operationB() override {
        std::cout << "ConcreteProductB2::operationB()" << std::endl;
    }
};

// 抽象工厂

class AbstractFactory {
public:
    virtual AbstractProductA* createProductA() = 0;
    virtual AbstractProductB* createProductB() = 0;
};

// 具体工厂1

class ConcreteFactory1 : public AbstractFactory {
public:
    AbstractProductA* createProductA() override {
        return new ConcreteProductA1();
    }

    AbstractProductB* createProductB() override {
        return new ConcreteProductB1();
    }
};

// 具体工厂2

class ConcreteFactory2 : public AbstractFactory {
public:
    AbstractProductA* createProductA() override {
        return new ConcreteProductA2();
    }

    AbstractProductB* createProductB() override {
        return new ConcreteProductB2();
    }
};

int main() {
    // 使用具体工厂1创建产品

    AbstractFactory* factory1 = new ConcreteFactory1();
    AbstractProductA* productA1 = factory1->createProductA();
    AbstractProductB* productB1 = factory1->createProductB();
    productA1->operationA();
    productB1->operationB();

    // 使用具体工厂2创建产品

    AbstractFactory* factory2 = new ConcreteFactory2();
    AbstractProductA* productA2 = factory2->createProductA();
    AbstractProductB* productB2 = factory2->createProductB();
    productA2->operationA();
    productB2->operationB();

    delete factory1;
    delete factory2;
    delete productA1;
    delete productB1;
    delete productA2;
    delete productB2;

    return 0;
}

In this example, the abstract factory AbstractFactorydefines the interface for creating abstract products AbstractProductAand objects AbstractProductB. Concrete factories ConcreteFactory1and ConcreteFactory2implement this interface respectively, and create concrete products ConcreteProductA1, ConcreteProductA2, , ConcreteProductB1and ConcreteProductB2.

4. The relationship between simple factory pattern, factory pattern and abstract factory pattern

1. Simple factory mode and factory mode

(1) The biggest advantage of the simple factory model is that the factory class contains the necessary logical judgment; the disadvantage is that it violates the open-closed principle.

Because the class contains necessary logical judgments, if you add requirements, you need to modify the original logic code, and there is a risk of changing the previous good functions to cause problems.

(2) The factory model is the further abstraction and promotion of the simple factory model. Due to the use of polymorphism, the factory method pattern maintains the advantages of the simple factory pattern and overcomes its shortcomings.

But the disadvantage of the factory model itself is that because each product has a product, it is necessary to add a product factory class, which increases the amount of additional development.

At this time, you can use "reflection" to solve the problem of avoiding branch judgment. ----Abstract factory pattern.

2. Abstract factory pattern and factory pattern

(1) Different purposes:

  • The Abstract Factory pattern aims to provide an interface to create a series of related or interdependent objects. It abstracts a group of related products into a factory, and the client creates products through this factory, thereby achieving decoupling.
  • The Factory Method pattern aims to define an interface for creating objects, but defer concrete instantiation to subclasses. Each subcategory can create its own specific product as needed.

(2) The structure is different:

  • The Abstract Factory pattern aims to provide an interface to create a series of related or interdependent objects. It abstracts a group of related products into a factory, and the client creates products through this factory, thereby achieving decoupling.
  • The Factory Method pattern aims to define an interface for creating objects, but defer concrete instantiation to subclasses. Each subcategory can create its own specific product as needed.

(3) Different focus points:

  • The Abstract Factory pattern aims to provide an interface to create a series of related or interdependent objects. It abstracts a group of related products into a factory, and the client creates products through this factory, thereby achieving decoupling.
  • The Factory Method pattern aims to define an interface for creating objects, but defer concrete instantiation to subclasses. Each subcategory can create its own specific product as needed.

In general, the abstract factory pattern is suitable for scenarios that need to create a set of related products at one time, while the factory method pattern is suitable for scenarios that need to create different products according to different situations.

Guess you like

Origin blog.csdn.net/bigger_belief/article/details/131855971