Design mode--simple factory mode

一: Introduction

Simple factory mode can not be said to be a design pattern, also known as Static Factory Method mode, which belongs to 类制作Mode, it is probably more appropriate to say that it is a programming habit. Because it is at least one of the Gof23 design patterns. But it is often used in actual programming, and the idea is very simple, it can be said that it is a guide to the factory method mode.

Consider a simple software application scenario, a software system can provide more Buttons with different appearances (such as round buttons, rectangular buttons, diamond buttons, etc.), these buttons are derived from the same base class (such as base class for fruit), but in inheritance Different subclasses modify some of the attributes so that they can render different appearances .

If we want to use these buttons, we don't need to know these specific buttons. The name of the class, you only need to know a parameter @|@| of the button , and provide a convenient ,并提供一个调用方便的方法, and pass the parameter to the method to return a corresponding button. Object, at this point, you can use the simple factory mode.

模式设计Simple Factory Pattern: Also known as the Static Factory Method mode, it belongs to the class creation mode. In simple factory mode, you can return instances of different classes depending on the parameters. The simple factory pattern specifically defines a class to be responsible for creating instances of other classes, and the created instances usually have a common parent class.

模式结构Simple factory mode contains the following roles: Factory: Factory role Product: abstract product role ConcreteProduct: The specific product role

Factory Role (

@) is the core of the simple factory model, which is responsible for implementing instances of all specific product classes. Factory classes can be called directly by the outside world to create the required product objects.

Abstract Product Role (

@) is the parent of all specific product roles and is responsible for describing the common interfaces common to all instances.

Concrete Product

Inherit from the abstract product role, generally multiple, is the creation goal of the simple factory model. The factory class returns a specific product of the role.

UML图

real life exampleEvery time you attend a different party or meet different people, you may not wear the same clothes, for example, you are going to have a new one with you this morning. When the customer meets, you may say to your wife: Wife, give a business suit (parameters), I want to see a customer of mine, your wife (factory class) receives your request (business equipment parameters), Take out a business suit (specific product) from the closet and hand it to you. The whole process is complete. You may have different clothes according to different conditions, but the clothes you want are already in your closet. Moreover, each blouse belongs to the same abstraction, that is, they can inherit from an abstract class or interface, and each of these clothes has certain characteristics, which are conditions. Then when you want, you can tell your wife a feature, and she will serve you according to this feature. This is the application of a typical simple factory model.

模式Instance and ResolutionProduct: Abstract Product Role ICoat.cs

@namespace SimpleFactory
{
    /// <summary>
    /// Abstract product category: tops
    /// </summary>
    Public interface ICoat
    {
        Void GetYourCoat();
    }
}

ConcreteProduct: Specific product role

BusinessCoat.cs

using System;

Namespace SimpleFactory
{
    /// <summary>
    /// Specific product categories: business tops
    /// </summary>
    Public class BusinessCoat : ICoat
    {
        Public void GetYourCoat()
        {
            Console.WriteLine("Business Top");
        }
    }
}

FashionCoat.cs

using System;

Namespace SimpleFactory
{
    /// <summary>
    /// Specific product categories: fashion tops
    /// </summary>
    Public class FashionCoat : ICoat
    {
        Public void GetYourCoat()
        {
            Console.WriteLine("fashion top");
        }
    }
}

Factory: Factory role Factory.cs

using System;

Namespace SimpleFactory
{
    /// <summary>
    /// The core part of the simple factory pattern: the factory class
    /// </summary>
    Public class factory
    {
        Public ICoat CreateCoat(string styleName)
        {
            Switch (styleName.Trim().ToLower())
            {
                Case "business": //Business Tops
                    Return new BusinessCoat();
                Case "fashion"://fashion top
                    Return new FashionCoat();
                Default:
                    Throw new Exception("There is no such thing as you want");
            }
        }
    }
}

Program.cs

Using System;

Namespace SimpleFactory
{
    /// <summary>
    /// Customer class
    /// </summary>
    Class client
    {
        Static void Main(string[] args)
        {
            ICoat food;
            Try
            {
                Factory factory = new Factory();
                Console.Write("Please select: fashion top fashion, business shirt business\t");
                String choice = Console.ReadLine();
                Switch (choice)
                {
                    Case "fashion"://fashion top
                        Console.Write ("I want a fashion shirt\t");
                        Food = factory.CreateCoat("fashion");
                        food.GetYourCoat();
                        Break;
                    Case "business": //Business Tops
                        Console.Write ("I want a business shirt\t");
                        Food = factory.CreateCoat("business");
                        food.GetYourCoat();
                        Break;
                    Default:
                        Console.Write("There is no clothes you want \t");
                        Break;
                }
                Console.ReadLine();
            }
            Catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
    }
}

模式分析 Separating the creation of an object from the business processing of the object itself can reduce the coupling degree of the system, making it relatively easy to modify both. When calling the factory method of the factory class, since the factory method is a static method, it is very convenient to use, can be called directly by the class name, and only need to pass a simple parameter Yes In actual development, you can also save the parameters passed in the configuration file in XML format when calling, and you don't need to modify any source code when modifying parameters. The biggest problem with the simple factory model is that the factory class has a relatively heavy responsibilities, and adding new products requires modifying the judgment logic of the factory class, which is contrary to the opening and closing principle. The main point of the || simple factory pattern is: When you need something, just pass in the correct parameters and you can get the objects you need without knowing the details of their creation. 简单工厂模式的要点在于:当你需要什么,只需要传入一个正确的参数,就可以获取你所需要的对象,而无须知道其创建细节。

Mode Advantages and Disadvantages

  • The advantages of the simple factory model

Factory class contains the necessary judgment logic to determine when to create an instance of the product class, the client can be exempted from directly creating product objects. Responsibility, but only “consumption” of products; the simple factory model achieves a division of responsibility through this approach, which provides specialized factory classes for creating objects. The client does not need to know the class name of the specific product class created. It only needs to know the parameters corresponding to the specific product class. For some complex class names, the user's memory can be reduced by the simple factory mode. By introducing a configuration file, it is possible to replace and add new specific product classes without modifying any client code, which increases the flexibility of the system to some extent.

  • The shortcomings of the simple factory model

Since the factory class concentrates all product creation logic, once it does not work properly, the entire system will be affected. Using the simple factory mode will increase the number of classes in the system, increasing the complexity and difficulty of understanding the system. The system expansion is difficult. Once the 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. The simple factory pattern caused the factory role to fail to form an inheritance-based hierarchical structure due to the use of the static factory method.

Mode Applicable EnvironmentThe simple factory mode can be used in the following cases: The factory class is responsible for creating fewer objects: because the number of objects created is small, the business logic in the factory method is not too complex. The client only knows the parameters of the incoming factory class, and does not care about how to create the object: the client does not need to care about the creation details, even the class name does not need to be remembered, only need to know the parameters corresponding to the type.

小结The creation model abstracts the instantiation process of the class and separates the creation of the object from the use of the object. The simple factory pattern, also known as the static factory method pattern, is a class-created pattern. In simple factory mode, you can return instances of different classes depending on the parameters. The simple factory pattern specifically defines a class to be responsible for creating instances of other classes, and the created instances usually have a common parent class. The simple factory pattern consists of three roles: the factory role is responsible for implementing the internal logic for creating all instances; the abstract product role is the parent of all objects created, and is responsible for describing the common interfaces common to all instances; the specific product role is to create the target, all The created object acts as an instance of a concrete class for this role. The point of the simple factory pattern is that when you need something, you only need to pass in the correct parameters to get the object you need without knowing the details of its creation. The biggest advantage of the simple factory model is the separation of the The object is created by handing it over to a specialized factory class, but its biggest drawback is that the factory class is not flexible enough. Adding new concrete products requires modifying the judgment logic code of the factory class. When there are many products, the factory method code will be very complicated. . Simple factory mode applies: The factory class is responsible for creating fewer objects; the client only knows the parameters of the incoming factory class, and does not care how to create the object.

In the case that I don’t understand the simple factory, I turned to a blog that is relatively close to life and easy to understand. I can understand it.

I hope it will be useful to you, now also for this simple factory. With a preliminary understanding, I hope to learn more in the later practice.