The Simple Factory pattern is not strictly a design pattern, but rather a programming habit.

define

Simple Factory Pattern: Also known as Static Factory Method Pattern, it belongs to the class 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.

structure

Simple factories contain the following roles:

  • Factory: The Factory role is responsible for creating different instances based on different parameters.

  • IProduct: Interface to all product instances of the abstract product role, responsible for describing the behavior of all product instances.

  • Product(A B ..) : Concrete product roles Instances of all products that implement abstract product definition code

Example scenario:

The scenario of simple factory application is quite correct. According to the author’s understanding, the scenario demand encountered by the author in his work is taken as an example: the platform conducts an air ticket purchase business and connects with two suppliers A and B. After the user selects the air ticket, the platform takes the air ticket to the supplier to place an order. When placing an order, according to the air ticket provided by the supplier to the corresponding supplier to place an order.

The first step is to define an order interface.

Public interface IVender {/** */ void order(); }Copy the code

Then, the ordering methods of A and B suppliers are implemented respectively.

public class VendorA implements IVender {
    @Override
    public void orderPrintln () {system.out.println ();"Supplier A placed the order successfully, time of placing the order"+ new Date()); }}Copy the code
public class VendorB implements IVender {
    @Override
    public void orderPrintln () {system.out.println ();"B supplier placed the order successfully, and the order time:"+ new Date()); }}Copy the code

We then define a factory class that creates and returns a different vendor instance for each incoming parameter request, and throws an exception if an invalid parameter is encountered.

public class VendorFactory {

    public static IVender createVendor(String type) {
        switch (type) {
            case "A":
                return new VendorA();
            case "B":
                return new VendorB();
            default:
                throw new RuntimeException("Supplier does not exist"); }}}Copy the code

Finally, the call is made by our client:

public class Client {
    public static void main(String[] args) {
        String type = "A";
        IVender iVender = VendorFactory.createVendor(type); iVender.order(); }}Copy the code

If we all write in one class:

public class Client2 {
    private static final String TYPE_A = "A";
    private static final String TYPE_B = "B";

    public static void main(String[] args) {
        String type = "A";
        if (Objects.equals(TYPE_A, type) {// A = system.out.println ("Supplier A placed the order successfully, time of placing the order" + new Date());
        } else if (Objects.equals(TYPE_B, type) {// B: system.out.println (system.out.println ("Supplier A placed the order successfully, time of placing the order" + new Date());
        } else {
            throw new RuntimeException("Supplier does not exist"); }}}Copy the code

In the second way, if the supplier orders more logic, the client will become very complicated, and the later maintenance will be a disaster. If a new vendor is added, it will make a major change to this class, which clearly violates the open closed principle and Demeter’s Law.

advantages

  • The factory class contains the necessary judgment logic to decide when to create an instance of a product class, freeing clients from the responsibility of directly creating product objects and simply “consuming” the product; The simple factory pattern achieves this separation of responsibilities by providing specialized factory classes for creating objects.
  • The client does not need to know the class name of the created specific product class, but only needs to know the corresponding parameters of the specific product class. For some complex class names, simple factory mode can reduce the memory of users.
  • By introducing configuration files, new specific product classes can be replaced and added without modifying any client code, increasing the flexibility of the system to some extent.

disadvantages

  • Because the factory class centralizes all product creation logic, if it doesn’t work properly, the entire system suffers.
  • Using the simple factory pattern will increase the number of classes in the system, increasing the complexity and understanding of the system at some point.
  • It is difficult to expand the system. Once new products are added, the factory logic has to be modified. If there are many product types, the factory logic may be too complex, which is not conducive to the expansion and maintenance of the system.
  • The simple factory pattern uses a static factory approach that prevents the factory roles from forming an inheritance-based hierarchy.

Usage scenarios

The simple factory pattern can be used when:

  • The factory class is responsible for creating fewer objects: Because there are fewer objects created, the business logic in the factory method is not too complicated.
  • The client only knows the parameters passed into the factory class, not 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.

conclusion

  • The creation pattern abstracts the instantiation process of a class, separating object creation from object usage.
  • The simple factory pattern, also known as the static factory method pattern, belongs to the class-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.
  • The simple factory pattern contains three roles: the factory role implements the internal logic that creates 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; A concrete product role is a creation target, and all created objects act as instances of a concrete class of that role.
  • The point of the simple factory pattern is that when you need something, you can just pass in the right argument and get the object you need without knowing the details of how it was created.
  • The greatest advantage of simple factory pattern is to realize the use of object creation and separation, the object creation to the specialized factory class is responsible for, but the biggest drawback is that the factory class is not flexible, adding new specific products need to modify the factory class judgment logic code, and are too many products, the factory method code will be very complicated.
  • The simple factory pattern applies when the factory class is responsible for creating fewer objects; The client only knows the parameters passed into the factory class and does not care how the object is created.