Design pattern learning notes: simple factory pattern

1 Definition

Simple Factory Pattern: defines a factory class, which can return different instances according to different parameters. The created instances usually have a common parent class.

Because the method used to create instances in the simple factory mode is a static method, the simple factory mode is also called the static factory method mode, which belongs to the class creation mode.

Although the simple factory pattern is not one of the 23 GoF23 design patterns, it is widely used in practice and can be used as a basis for learning "factory method pattern" and "abstract factory pattern".

2 Structure

It can be seen from the figure that there are three roles:

  • Factory (factory role): that is, the factory class is 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. A static factory method is provided in the factory class to obtain products
  • Product (abstract product role): it is the parent class of all objects created by the factory class and encapsulates the public methods of various product objects. Product will improve the flexibility of the system, so that only one general factory product method needs to be defined in the factory class, because all the created concrete products are its subclass objects
  • ConcreteProduct (concrete product role): all created objects act as instances of a concrete class of this role. Each specific product role inherits the abstract product role and needs to implement the abstract methods declared in the abstract product

3 examples

A company needs to develop a chart library that can provide charts with different appearances, such as bar charts, line charts, etc.

First, you can design an abstract chart class (here is an interface):

interface Chart
{
	void display();
}

Then various specific product classes (bar chart, line chart, pie chart, etc.) can implement this interface:

class HistogramChart implements Chart
{
    public HistogramChart()
    {
        System.out.println("Create a histogram");
    }

    public void display()
    {
        System.out.println("Display histogram");
    }
}

class PieChart implements Chart
{
    public PieChart()
    {
        System.out.println("Create pie chart");
    }

    public void display()
    {
        System.out.println("Show pie chart");
    }
}

class LineChart implements Chart
{
    public LineChart()
    {
        System.out.println("Create line chart");
    }

    public void display()
    {
        System.out.println("Show line chart");
    }
}

Finally, the factory class is added with enumeration parameters for convenience:

class Factory
{
    public static Chart getChart(Charts charts)
    {
        switch(charts)
        {
            case PIE_CHART:
                return new PieChart();
            case LINE_CHART:
                return new LineChart();
            case HISTOGRAM_CHART:
                return new HistogramChart();
            default:
                return null;
        }
    }
}

enum Charts
{
    PIE_CHART,LINE_CHART,HISTOGRAM_CHART;
}

Test:

public static void main(String[] args) {
    Chart chart = Factory.getChart(Charts.LINE_CHART);
    chart.display();
}

4 simplification

To simplify the simple factory pattern, you can merge the abstract product class with the factory class and move the static method to the abstract product class:

In this way, subclass objects can be obtained through static methods of abstract product classes. The optimization code is as follows:

interface Chart
{
    void display();
    static Chart getChart(Charts charts)
    {
        switch(charts)
        {
            case PIE_CHART:
                return new PieChart();
            case LINE_CHART:
                return new LineChart();
            case HISTOGRAM_CHART:
                return new HistogramChart();
            default:
                return null;
        }
    }
}

5 main advantages

The main advantages of the simple factory model are as follows:

  • Separation of responsibilities: the simple factory mode realizes the separation of object creation and use. The factory class contains necessary judgment logic, which can decide when to create an instance of what product. The client can exempt the responsibility of directly creating product objects, just "consuming" products
  • Simplified memory: the client does not need to know the name of a specific product class, but only needs to know the corresponding parameters. Generally, constant strings or enumerations are used
  • Improve flexibility: you can introduce configuration files (xml, etc.) to add new specific product classes without modifying the client code to improve flexibility

6 main disadvantages

The main disadvantages of the simple factory model are as follows:

  • The factory class centralizes the creation logic of all products. Once it fails to work normally, the whole system will be affected
  • The introduction of factory classes will increase the number of classes in the system and increase the complexity and understanding difficulty of the system
  • It is difficult to expand the system. Once a new product is added, the factory logic has to be modified. When there are too many product types, the factory logic may be too complex, which is not conducive to system expansion and maintenance
  • The simple factory mode uses the static factory method, which makes the factory role unable to be based on the inherited hierarchical structure

7 applicable scenarios

  • The factory class is responsible for creating fewer objects. Because there are fewer objects, the business logic in the factory method will not be too complex
  • The client only needs to know the parameters passed into the factory class, and does not care about how to create objects

8 summary

Tags: Design Pattern

Posted by snipe7kills on Tue, 31 May 2022 04:12:26 +0530