In depth understanding of the simple factory pattern of Java design pattern

  • 2021-12-11 07:26:25
  • OfStack

Directory 1. What is Simple Factory Pattern 2. Structure of Simple Factory Pattern 3. Application Scenario of Simple Factory Pattern 4. Difference between Simple Factory Pattern and Factory Method Pattern 5. Similarities and Differences between Simple Factory Pattern and Policy Pattern 6. Advantages and Disadvantages of Simple Factory Pattern 7. Implementation of Simple Factory Pattern 8. Summary

1. What is the simple factory model

Simple factory pattern is also called static factory pattern. In essence, a factory class dynamically decides which instance of a product class (these product classes inherit from a parent class or interface) should be created according to the passed-in parameters. The goal for the creation of the simple factory pattern, where all objects created are instances of a concrete class that acts as this role.

In fact, the instantiation of a concrete class is handed over to a static factory method for execution. It does not belong to the 23 design patterns of GOF, but it is often used in reality, and the idea is very simple.

2. Structure of the Simple Factory Pattern

The Simple Factory pattern includes the following roles:

Factory : Factory role

Product Abstract product roles

ConcreteProduct : Specific product roles

工厂角色(Creator) 是简单工厂模式的核心,它负责实现创建所有具体产品类的实例。工厂类可以被外界直接调用,创建所需的产品对象。
抽象产品角色(Product) 是所有具体产品角色的父类,它负责描述所有实例所共有的公共接口。
具体产品角色(Concrete Product) 继承自抽象产品角色,1般为多个,是简单工厂模式的创建目标。工厂类返回的都是该角色的某1具体产品。

3. Simple Factory Pattern Application Scenarios

1. A few days ago, Apple just released IPhone Xs and iPhone XR, so the question comes. How many sizes of mobile phones do Apple's foundries produce?

1. It is up to the factory to decide which model of mobile phone to produce. Apple's factory is a factory class, which is the core class of simple factory model.

2. iPhoneX, iPhoneXs and iphoneXr are all Apple phones, but their models are different. Apple mobile phone class meets the abstract definition, and each model of mobile phone class is its concrete implementation.

2. Consider a simple software application scenario, A software system can provide multiple buttons with different appearances (such as round buttons, rectangular buttons, diamond buttons, etc.), These buttons all originate from the same base class, However, after inheriting the base class, different subclasses modify some properties so that they can take on different appearances. If we want to use these buttons without knowing the names of these specific button classes, we only need to know one parameter representing the button class, and provide a convenient method to call. If we pass this parameter into the method, we can return a corresponding button object. At this time, we can use the simple factory mode.

You can use the simple factory pattern in the following situations:

The factory class is responsible for creating fewer objects: Because fewer objects are created, the business logic in the factory method will not be too complex.
The client only knows the parameters passed in to the factory class, and doesn't care how to create the object: The client doesn't need to care about the creation details, and doesn't even need to remember the class name, but only needs to know the parameters corresponding to the type.

4. Difference between simple factory pattern and factory method pattern

Simple factory mode:

(1) The factory class is responsible for creating fewer objects. Because there are fewer objects created, the business logic in the factory method will not be too complicated.

(2) The client only knows the parameters passed in to the factory class, and doesn't care how to create the object.

Factory method mode:

(1) The client does not know the class of the object it needs.

(2) The abstract factory class specifies which object to create through its subclasses.

5. Similarities and differences between simple factory model and strategy model

Policy pattern and simple factory pattern look very similar, both of which realize the selection of different subclasses through polymorphism. This idea should be seen from the whole program.

From the perspective of using these two patterns, we will find that in the simple factory pattern, we only need to pass the corresponding conditions to get the desired object, and then implement the operation of the algorithm through this object.

In the policy mode, when using it, you must first create a class object you want to use, then pass the object as a parameter, and call different algorithms through this object.

In the simple factory pattern, the object is instantiated by selecting a class conditionally, while in the policy pattern, the user of the pattern is given the task of selecting the corresponding object, and it does not do the selection work itself.

Combined with the following code and the following definition, it is not difficult to see that the difference between the two is very subtle. Factory directly creates a specific object and uses the object to perform corresponding actions, while Context gives this operation to Context class, without creating a specific object, and the implementation code is encapsulated in one step. The client code does not need to know the specific implementation process.

6. Advantages and disadvantages of the simple factory model

Advantages:

The factory class is the key to the whole schema. It contains the necessary logical judgment to decide which concrete class object should be created according to the given information from the outside world.

By using factory classes, the outside world can get rid of the awkward situation of directly creating specific product objects, and only need to be responsible for "consuming" the objects.

It doesn't matter how these objects are created and organized. Clarifying their respective responsibilities and rights is beneficial to the optimization of the whole software architecture.

Disadvantages:

Because the factory class concentrates the creation logic of all instances, which violates the principle of opening and closing, all the creation logic is concentrated in one factory class;

The classes it can create can only be anticipated, and if new classes need to be added, the factory class needs to be changed.

When the number of specific product classes in the system is increasing, there may be a requirement for factory classes to create different instances according to different conditions.

This judgment of conditions and the judgment of specific product types are interlaced, which makes it difficult to avoid the spread of module functions and is very unfavorable to the maintenance and expansion of the system;

Open-close principle definition: 1 software entities such as classes, modules, and functions should be open for extensions and closed for modifications.

The open-closed principle means that when you design, you should always consider that this class is good enough. If you write it well, don't modify it. If new requirements come, we will add 1 class and finish it. If the original code can not move, it will not move. This principle has two features, one saying "open for extensions" and the other saying "closed for changes." In the face of requirements, changes to the program are made by adding new code, rather than changing existing code. This is the spirit of the "open-closed principle".

7. Implementation of the Simple Factory Pattern

First, create an "Apple Mobile Phone" class and define a method to obtain the size of the mobile phone


// Apple phone 
public abstract class ApplePhone {
    // Acquisition dimensions 
    protected abstract void getSize();
 }

Different models of Apple's mobile phones are "mobile phones".


public class IphoneX:ApplePhone{
    public void getSize() {
        Console.WriteLine("iPhoneX Screen :3.5 Inches ");
    }
}
public class IphoneXs:ApplePhone{
     public void getSize() {
        Console.WriteLine("iPhoneX Screen :4.5 Inches ");
    }
}
public class IphoneXR:ApplePhone{
    public void getSize() {
        Console.WriteLine("iPhoneX Screen :5.5 Inches ");
    }
}

Establish a "factory class" to produce different models of "mobile phone objects".


// Apple factory 
public class AppleFactory {
    public static ApplePhone createPhone(String model){
        ApplePhone applePhone = null;
        switch (model) {
            case"iPhoneX":
                applePhone = new IphoneX();
                break;
            case"iPhoneXs":
                applePhone = new IphoneXs();
                break;
            case"iPhoneXr":
                applePhone = new IphoneXR();
                break;
            default:
                break;
        }
        returnapplePhone;
    }
}

Finally, the client test class


public class Client {
    public static void main(String[] args) {
        ApplePhone applePhone ;
        applePhone = AppleFactory.createPhone("iPhoneX");
        applePhone.getSize();
        applePhone = AppleFactory.createPhone("iPhoneXs");
        applePhone.getSize();
        applePhone = AppleFactory.createPhone("iPhoneXr");
        applePhone.getSize();
    }
}

8. Summary

Creative pattern abstracts the instantiation process of classes, and can separate the creation process of objects from the use process of objects.

Simple factory pattern, also known as static factory method pattern, belongs to class creation pattern. In simple factory mode, you can return instances of different classes according to different parameters.

The simple factory pattern specifically defines one class to create instances of other classes, which usually have a common parent class.

The simple factory pattern contains three roles: the factory role is responsible for implementing the internal logic for creating all instances; The abstract product role is the parent class of all objects created, and is responsible for describing the common interface shared by all instances; The concrete product role is the creation target, and all created objects act as instances of a concrete class of this role.

The point of the simple factory pattern is that when you need something, you just need to pass in 1 correct parameter to get the object you need without knowing the details of its creation.

The greatest advantage of the simple factory pattern is that it separates the creation of objects from the use of objects, The factory class is responsible for creating objects, but its biggest disadvantage is that the factory class is not flexible enough, adding new specific products needs to modify the judgment logic code of the factory class, and when there are many products, the factory method code will be very complex.

The application of simple factory pattern includes: the factory class is responsible for creating fewer objects; The client only knows the parameters passed in to the factory class, and doesn't care how to create the object.

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: