Factory pattern of creative design pattern

1, Factory design mode

The factory model is similar to the factory in real life. In real life, users never relate to the detailed manufacturing process of an item, but directly purchase the final finished product. This is also the starting point of factory design pattern. The difference is that we should consider the problem from the perspective of the factory. Factory pattern can be divided into simple factory pattern, factory method pattern and abstract factory pattern

2, Detailed explanation of factory design mode

1. Simple factory mode

The simple factory mode is to create an actual object directly according to the passed parameters. The code example is as follows:

public class SimpleFactory {
    /**
     * @author yongrenyue
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    public Food create(String name) throws ClassNotFoundException {
        switch (name){
            case "cookie":
                return new Cookie(name);
            case "bread":
                return new Bread(name);
            default:
                throw new ClassNotFoundException("Factory can not produce!");
        }
    }
}

Some people may ask that the difference between this and directly new an object is that it is simply encapsulated, but it feels complicated. But don't forget that in the actual scenario, creating a new object may have dependencies. The code example is as follows:

public class SimpleFactory2 {
    /**
     * @author yongrenyue
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    public Food create(String name) throws ClassNotFoundException {
        switch (name){
            case "noodles":
                Flour flour = new Flour("yongrenyue", 231);
                Oil oil = new Oil("yongrenyue", 123);
                return new Noodles("lanzhou" , flour, oil);
            case "steamedbread":
                Flour flo = new Flour("yongrenyue", 231);
                return new SteamedBread(name, flo);
            default:
                throw new ClassNotFoundException("Factory can not produce!");
        }
    }
}

In this case, the flow and oil objects are required to create the noodles object, while the flow object is required to create the steamedread object. If you create these two objects yourself, it's acceptable to create one. What if you create 100? Do you have a little experience of the factory model.
However, this simple factory mode has great disadvantages. If you want to add new objects later, you must modify the SimpleFactory class. Moreover, as the number of objects to be created increases, the factory class will become larger and larger. The opening and closing principle in the design pattern requires the modification to be closed and the extension development to be closed, which obviously violates this principle. Therefore, there are the following factory method patterns and abstract factory method patterns.

2. Factory method mode

The above simple factory method pattern is that a factory can create all objects, but it is not friendly to scenes with new objects, which explicitly violates the opening and closing principle. The factory method mode weakens the ability of the factory and creates a new factory class for each object to be created, that is, it changes from a factory that can be created by any object to a specific factory. The noodles factory only generates noodles, while the bread factory only produces bread. Code examples are as follows:

//Noodles Factory
public class NoodlesFactory {
    public Noodles createFactory(){
        Flour fo = new Flour("yongrenyue", 123);
        Oil oil = new Oil("yongrenyue", 321);
        return new Noodles("lanzhou", fo, oil);
    }
}
//Bread Factory
public class BreadFactory {
    public Bread crateBread(String name){
        return new Bread("yongrenyue");
    }
}

When using, first create a factory instance of the object to be produced, and then create the corresponding object through the corresponding factory. The main problem solved by the factory method mode is the opening and closing principle violated by the simple factory. If you want to add a new type, you only need to create the corresponding factory class without modifying the existing factory class, which is in good compliance with the opening and closing principle. Examples of using factory method mode are as follows:

public static void main(String[] args) throws ClassNotFoundException {
        //FactoryMethod demo
        NoodlesFactory noodleFactory = new NoodlesFactory();
        noodleFactory.createNoodles().show();
        System.out.println("--------------------------------------");
        BreadFactory breadFactory = new BreadFactory();
        breadFactory.crateBread().show();

    }

3. Abstract factory mode

The abstract Factory pattern is a further abstraction on the Factory method pattern, extracts the Factory interface, and then implements the corresponding Factory through the implementation interface.

public interface Factory {
    Food create();
}

public class CookieFactory implements Factory{
    @Override
    public Food create() {
        return new Cookie("yongrenyue");
    }
}

public class SteamedBreadFactory implements Factory{
    @Override
    public Food create() {
        return new SteamedBread("yongrenyue", new Flour("yongrenyue", 123));
    }
}

When in use:

public static void main(String[] args) throws ClassNotFoundException {
        //FactoryMethod demo
       Factory factory = new SteamedBreadFactory();
       factory.create().show();
       System.out.println("--------------------------------------");
       factory = new CookieFactory();
       factory.create().show();
    }

The abstract factory has another layer of abstraction based on the factory method pattern, so it is more convenient to use. The top-level interfaces are the same, which can easily replace the factory that creates objects. However, abstract factories also have disadvantages. If new functions need to be added to the factory interface, the interface and all factories implementing the interface need to be modified at the same time. Therefore, abstract factories are suitable for horizontal expansion of similar factories.

summary

The above is the factory pattern in the creative design pattern, involving the following codes: https://gitee.com/yongrenyue/design-pattern.
If there is any mistake, please criticize and correct it. If you make a mistake, you can't make a contribution.

Tags: Java Design Pattern

Posted on Fri, 26 Nov 2021 21:48:22 -0500 by Cheers