Model motivation

Let’s say your phone is due for an upgrade and you’re looking to buy one, so you click on an online store like JD to find a store that sells multiple brands of mobile phones at once.

It is assumed that only the mobile phone brand is distinguished, and multiple mobile phone types under this brand are not distinguished (for example, P30 and P40 are collectively referred to as Huawei mobile phones without segmentation). At the same time, the operating system of a mobile phone has unique differentiation in the store.

Then you find a store that offers phones from several different operating systems: Huawei, Samsung, Apple. These phones are all derived from the same base class (abstract phone class), but after inheriting the base class, different subclasses modify some of their properties to give them a different look and performance. At this point, you only need to know the phone’s operating system, name or other parameters, and you can submit an order to get the phone behind the parameters.

In this process, the user (you) does not need to create the phone directly, but hands it over to the factory (shop owner) to produce/provide the specified product, and the user only “consumes” the product. This pattern is also known as the simple factory pattern.

It avoids the following hard-to-maintain code on the client side:

define

The simple factory pattern is also called the static factory method pattern, which belongs to the creation pattern.

In the simple factory pattern, you can return instances of different classes depending on the parameters. The simple factory pattern specifically defines a class that is responsible for creating instances of other classes, which usually have a common parent class.

UML class diagrams

The model structure

The simple Factory pattern contains the following roles:

  • Factory:The factory classIs responsible for implementing the internal logic that creates all instances
  • Product:Abstract product classIs the parent class of all objects created and is responsible for describing the common interface shared by all instances
  • ConcreteProduct:Specific product categoryCreates an object that acts as an instance of this concrete class

More instances

The sample code

Product.java

public abstract class Product {
    public abstract void use(a);
}
Copy the code

ConcreteProductA.java

public class ConcreteProductA extends Product {
    @Override
    public void use(a) {
        // TODO: ConcreteProductA use..}}Copy the code

ConcreteProductB.java

public class ConcreteProductB extends Product {
    @Override
    public void use(a) {
        // TODO: ConcreteProductB use..}}Copy the code

Factory.java

public class Factory {
    // You can implements it by switch-case or if-else too
    private static Map<String, Product> factoryMap = new HashMap<>();

    static {
        factoryMap.put("A".new ConcreteProductA());
        factoryMap.put("B".new ConcreteProductB());
    }

    public static Product createProduct(String type) {
        returnfactoryMap.get(type.toUpperCase()); }}Copy the code

The advantages and disadvantages

➤ A bookmarking factory class can save clients from creating product objects directly and simply “consuming” them. By providing a factory class for creating objects, the simple factory pattern realizes the division of responsibility, and also realizes the separation of object creation from object use, which conforms to the principle of single responsibility.

✔ The cleavage client does not need to know the name of the specific product class being created. Instead, it can provide parameters associated with the specific product class. For more complex class names, a simple factory pattern can reduce memory.

❌ Because the factory class centralizes the creation logic for all products (centralized), the entire system is affected if it does not work properly (single point of failure).

❌ It is difficult to expand the system. Once new products are added, the code logic of the factory class has to be modified, which is inconsistent with the open and close principle. It may be difficult to maintain the factory class when there are too many products.

❌ The simple factory pattern uses a static factory approach that prevents the factory roles from forming an inheritance-based hierarchy.

Applicable scenario

The simple factory pattern is recommended when:

  • The factory class is responsible for creating fewer objects: Because there are fewer objects created, the business logic in the method is not too complicated.
  • The client only knows the parameters passed into the factory class and doesn’t care how the object is created: the client doesn’t need to care about the creation details or even remember the class name, just the parameters that the type corresponds to.

Simple Factory Pattern in the JDK

(1) The simple factory pattern is widely used in JDK libraries, such as the utility class java.text.dateFormat, which is used to format a local date or time

(2) Java encryption technology, keygenerator.getinstance () according to different parameters to obtain different encryption algorithm KeyGenerator

The last

👆 previous article: “Design Patterns” Understand the seven principles of object-oriented design and eliminate bad smells in code

👇 Next: “Design Patterns” 🏭 Factory Method

❤️ Good code without explanation, pay attention to the “rip design patterns” column, with me to learn design patterns, your code can be as elegant as poetry!

❤️ / END/If this article is helpful to you, click a “like” to support it, your support is my biggest motivation!