Design Pattern | Abstract Factory Pattern

1 | Overview of the abstract factory pattern

1.1 Basic idea

The factory method pattern solves the problem of too heavy responsibilities of the factory class in the simple factory pattern by introducing the factory hierarchy. However, because each specific factory in the factory method pattern has only one or a set of overloaded factory methods, only one factory method can be produced. This kind of products may result in a large number of factories in the system, which will inevitably increase the overhead of the system. Sometimes it may be necessary for a factory to provide multiple product objects instead of a single product object. For example, an electrical appliance factory can produce multiple electrical appliances such as televisions, refrigerators, and air conditioners, rather than just one type of electrical appliance. At this point, you can consider combining some related products into a "product family", which is produced by the same factory. This is the basic idea of ​​the abstract factory model that will be learned in this chapter.

1.2 Noun explanation

The abstract factory pattern is one of the commonly used creational design patterns, which has a higher degree of abstraction than the factory (method) pattern. In the factory (method) mode, each specific factory only needs to produce a specific product, but in the abstract factory mode, a specific factory can produce a group of related specific products, such a group of products is called a product family , Each product in the product family belongs to a certain product inheritance hierarchy.

 Before understanding the abstract factory pattern, we first understand the following two noun concepts:

  • (1) Product hierarchical structure : The product hierarchical structure is the inheritance structure of the product. For example, an abstract category is TV, and its subcategories include Haier TV, Hisense TV, and TCL TV, then abstract TV and specific brand TV A product level structure is formed between them. Abstract TV sets are the parent category, and specific brand TV sets are its subcategories.
  • (2) Product family : In the abstract factory model, product family refers to a group of products produced by the same factory and located in different product hierarchical structures. For example, Haier TVs and Haier refrigerators produced by Haier Electrical Appliances Factory, Haier TVs are in the TV product hierarchy, Haier refrigerators are in the refrigerator product hierarchy, Haier TVs and Haier refrigerators form a product family.

1.3 Definition of abstract factory pattern

The abstract factory pattern provides a solution for creating a set of objects. Compared with the factory model, the specific foreman in the abstract factory model is not only to create a product, but to create a family of products.

  • Abstract factory pattern: Provide an interface for creating a series of related or interdependent objects without specifying their specific classes.
  • Abstract Factory Pattern: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

The abstract factory pattern is also called the tool (Ki) pattern , which is an object creation pattern.


2 | Structure and realization of abstract factory

2.1 The structure of
the abstract factory pattern In the abstract factory pattern, each concrete factory provides multiple factory methods to produce a variety of different types of products, and these products constitute a product family. 
The abstract factory pattern includes the following 4 roles:

  • (1) AbstractFactory : It declares a set of methods for creating a family of products, and each method corresponds to a product.
  • (2) ConcreteFactory (concrete factory) : It implements the method of declaring and creating products in the abstract factory, and generates a set of concrete products. These products constitute a product family, and each product is located in a certain product hierarchy.
  • (3) AbstractProduct (abstract product) : It declares the interface for each product, and declares the business methods of the product in the abstract product.
  • (4) ConcreteProduct (concrete product) : It defines the concrete product object produced by the concrete factory, and realizes the business method declared in the abstract product interface.

2.2 Implementation of the abstract factory pattern
In the abstract factory, multiple factory methods are declared to create different types of products. The abstract factory can be an interface, an abstract class or a concrete class. The typical code is as follows:
an example of application, a company wants to develop a set of skin library, desktop software based on the .NET platform to beautify the interface.

Code design:

  • The interface ISkinFactory acts as an abstract factory, and its subclasses SpringSkinFactory and SummerSkinFactory act as concrete factories.
  • Interfaces IButton, IComboBox and ITextFiled act as abstract products, and its subclasses SpringButton, SpringComboBox, SpringTextFiled and SummerButton, SummerComboBox, and SummerTextFiled act as concrete products.

ISkinFactory

/// <summary>
/// 界面皮肤工厂接口,充当抽象工厂
/// </summary>
interface ISkinFactory
{
    IButton CreateButton();
    ITextFiled CreateTextFiled();
    IComboBox CreateComboBox();
}

SpringSkinFactory

/// <summary>
/// Spring 皮肤工厂,充当具体工厂
/// </summary>
class SpringSkinFactory : ISkinFactory
{
    public IButton CreateButton()
    {
        return new SpringButton();
    }

    public IComboBox CreateComboBox()
    {
        return new SpringComboBox();
    }

    public ITextFiled CreateTextFiled()
    {
        return new SpringTextFiled();
    }
}

IButton

/// <summary>
/// 按钮接口,充当抽象产品
/// </summary>
interface IButton
{
    void Display();
}

SpringButton 

/// <summary>
/// Spring 按钮类,充当具体产品
/// </summary>
class SpringButton : IButton
{
    public void Display()
    {
        Console.WriteLine("显示浅绿色的按钮。");
    }
}

Main call in the client Program

//xml配置文件与反射方式扩展
// 1.读取【App.config】配置文件
string factoryString = ConfigurationManager.AppSettings["spring"];
ISkinFactory skinFactory = (ISkinFactory)Assembly.Load("AbstractFactoryPattern").CreateInstance(factoryString);
IButton ibtn = skinFactory.CreateButton();
IComboBox iComBox = skinFactory.CreateComboBox();
ITextFiled iTextFiled = skinFactory.CreateTextFiled();

ibtn.Display();
iComBox.Display();
iTextFiled.Display();

Other implementations are similar, omitted here, see the complete code demo =》https://gitee.com/dolayout/DesignPatternOfCSharp/tree/master/DesignPatternOfCSharp/AbstractFactoryPattern

3 | Inclination of the opening and closing principle in the abstract factory model

The above interface skin library can easily add new types of skin libraries, but this design scheme has a very serious problem: if the design is not comprehensive at the beginning of the design, a certain type of interface component (such as a radio button) is forgotten. Provide style display under different skins, then you will find it very troublesome to add radio buttons to the system. It is impossible to add radio buttons under the premise of satisfying the principle of opening and closing. The reason is that the abstract factory ISkinFactory does not provide creating radio buttons at all. If you need to add this button, you must first modify the abstract factory interface ISkinFactory, add a method to create a radio button in it, and then modify the specific factory classes in the derived classes one by one, and add corresponding methods to use them in different skin libraries. To create a radio button, you also need to modify the client, otherwise the radio button cannot be used in the existing system.

The abstract factory pattern cannot solve such problems well, and this is also the biggest disadvantage of the abstract factory pattern. In the abstract factory, it is convenient to add a new product family, but it is troublesome to add a new product hierarchical structure. This feature of the abstract factory model is called the tendency of the opening and closing principle. The principle of opening and closing requires the system to be open for extension and closed for modification. The purpose of enhancing its functions through extension is to achieve the purpose of enhancing its functions. For systems involving multiple product families and multiple product level structures, its function enhancements include the following two points:

  • (1) Add product family: Corresponding to the newly added product family, the abstract factory model well supports the principle of opening and closing. You only need to add specific products and correspondingly add a new specific factory. There is no need for existing codes. Any modification.
  • (2) Adding a new product level structure: Corresponding to adding a new product level structure, it is necessary to modify all factory roles, including abstract factory classes, and add new product methods to all factory classes, which violates the principle of opening and closing. .

The abstract factory model is a sloping way to meet the opening and closing principles, so the designer is required to consider comprehensively at the beginning of the design, otherwise it will cause major changes to the system and bring many troubles and risks to the subsequent maintenance work.

4 | The advantages and disadvantages and applicable scenarios of the abstract factory pattern

The abstract factory pattern is a further extension of the factory (method) pattern. Because it provides a more powerful factory class and has better scalability, it is widely used in software development, especially in some frameworks and API libraries In the design. Abstract factory pattern is one of the most commonly used design patterns in software development.
4.1 The main advantages of the abstract factory pattern

  • (1) The abstract factory pattern isolates the generation of concrete classes, so that the client does not need to know what was created. Due to this isolation, it becomes relatively easy to replace a concrete factory. All concrete factories implement the public interfaces defined in the abstract factory. Therefore, only by changing the instance of the concrete factory, the entire software system can be changed to some extent. the behavior of.
  • (2) When multiple objects in a product family are designed to work together, it can ensure that the client always uses only the objects in the same product family.
  • (3) The abstract factory model is very convenient to add new product families, without modifying the existing system, and conforms to the principle of opening and closing.

4.2 The main shortcomings of the abstract factory model. It
is troublesome to add a new product level structure, requiring major modifications to the original system, and even the need to modify the abstract layer code, which obviously brings greater inconvenience and violates the principle of opening and closing.

4.3 Applicable environment of abstract factory pattern

  • (1) A system should not depend on the details of how product class instances are created, combined, and expressed. This is important for all types of factory models. Users do not need to care about the creation process of objects, and solve the creation and use of objects. Coupled.
  • (2) There is more than one product family in the system, but only one product family is used each time. Users can dynamically change the product family through configuration files and other methods, and can also easily add new product families.
  • (3) Products belonging to the same product family will be used together, and this constraint must be reflected in the design of the system. Products in the same product family can be unrelated objects, but they all have some common constraints, such as buttons and text boxes under the same operating system. There is no direct relationship between buttons and text boxes, but they all belong to For a certain operating system, there is a common constraint at this time: the type of operating system.
  • (4) The product grade structure is stable. After the design is completed, no new product grade structure will be added to the system or the existing product grade structure will not be deleted.

Guess you like

Origin blog.csdn.net/ChaITSimpleLove/article/details/114496161