Java Design Pattern - Factory Pattern

    The factory pattern is one of the more commonly used creational patterns among the 23 Java design patterns. In daily applications, the Java factory pattern is divided into three types: simple factory pattern, factory method pattern and abstract factory pattern. Among them, the simple factory pattern, also known as the static factory pattern, does not belong to the 23 design patterns; the factory method pattern and the abstract factory pattern are further interpretations of the Java factory pattern on the basis of the simple factory pattern.

One, the simple factory pattern: 

    1, UML class:

    

     * In the simple factory mode, there is a factory model of a commodity and an upwardly extracted commodity interface;

     * The specific commodity type is used as the implementation class of the commodity interface, and depends on the factory model class; 

     * The factory model creates a specific commodity model through the factory() method and polymorphically returns the specific commodity object;

     * The commodity reference returned by polymorphism points to the specific commodity object;

     * In simple terms, the simple factory pattern is to encapsulate the if-else level in the code to make the code function more specific;

2. Code Analysis

    * Factory class

public class SimpleFactory {

    public static Milk createMilk(String name) {
        if("蒙牛".equals(name)) {
            return new MengNiuMilk();
        } else if("伊利".equals(name)) {
            return new YiLiMilk();
        } else if("特仑苏".equals(name)) {
            return new TeLunSuMilk();
        }
        return null;
    }
}

    * Commodity interface

public interface Milk {
    String getName();
}
    * Commodity
public class MengNiuMilk implements Milk {

    @Override
    public String getName() {
        return "Mengniu";
    }
}
public class TeLunSuMilk implements Milk {

    @Override
    public String getName() {
        return "Tronsu";
    }
}
public class YiLiMilk implements Milk {

    @Override
    public String getName() {
        return "Erie";
    }
}

    * test class

public class SimpleFactoryTest {

    public static void main(String[] args) {
        Milk milk = SimpleFactory.createMilk("蒙牛");
        System.out.println(milk.getName());
    }
}

3. Analysis of advantages and disadvantages

    * The simple factory pattern entrusts the creation of specific objects to the factory, which simplifies the code structure to a certain extent and provides a paradigm for specific creation as a whole.

    * The simple factory pattern just extracts the action of creating objects uniformly upwards. In the factory, if a new object branch needs to be added in the factory because the addition of specific commodity objects may need to be generated, it does not conform to the open and closed principle in the Java design principle. In complex business scenarios, business requirements cannot be met.

Second, the factory method pattern: 

    The factory method pattern is the improvement of the simple factory pattern. The factory method pattern provides an upward abstract factory class. Each concrete object creates a factory and inherits the abstract factory class. The abstract factory class provides a unified method for creating objects, and the specific factory class is rewritten to create specific objects;

1, UML class: 


    * The factory method pattern provides upward commodity classes and factory classes;

    * Create several concrete factory classes to implement abstract factories;

    * The specific commodity class implements the commodity interface and depends on its corresponding specific factory class;

    * Polymorphically create factories, and return specific commodity objects through factory polymorphism to complete object creation;

2. Code

    * Abstract factory

public abstract class FunctionFactory {

    public abstract Milk createMilk();
}

    * Specific factory

public class MengNiuFactory extends FunctionFactory {

    @Override
    public Milk createMilk() {
        return new MengNiuMilk();
    }
}
public class TeLunSuFactory extends FunctionFactory {

    @Override
    public Milk createMilk() {
        return new TeLunSuMilk();
    }
}
public class YiLiFactory extends FunctionFactory {

    @Override
    public Milk createMilk() {
        return new YiLiMilk();
    }
}

* Commodities and specific commodities are similar to the simple factory model;

* test class

public class FunctionFactoryTest {

    public static void main(String[] args) {
        FunctionFactory factory = new TeLunSuFactory();
        Milk milk = factory.createMilk();
        System.out.println(milk.getName());

        FunctionFactory factory1 = new MengNiuFactory();
        Milk milk1 = factory1.createMilk();
        System.out.println(milk1.getName());
    }
}

3. Analysis of advantages and disadvantages

    * The factory method pattern makes up for the problem of too many branches and difficult code maintenance in the simple factory pattern, and conforms to the Java open-closed principle.

    * For each commodity added, a specific commodity category and factory category need to be added correspondingly, which inevitably results in a complex overall category structure. Of course, it is also a common problem of the commodity model;

Third, the abstract factory pattern

    Similarly, both the factory method pattern and the abstract factory pattern will make the class system complex in the whole system structure, but the difference is: the factory method pattern is an irregular class structure with complex structure, while the abstract factory pattern is a regular class structure with complex structure. . Abstract Factory puts forward the concept of "product family", which is an upward integration of the simple factory pattern and the factory method pattern, and uses the respective advantages of the simple factory pattern and the factory method pattern to carry out the modular processing of the overall structure;

1, UML class diagram


    * The abstract factory pattern provides abstract factory classes and corresponding abstract product interfaces for creating product families;

    * The concrete factory implements the abstract factory to override the abstract method;

    * Each specific product can extract the factory class upwards according to the simple factory model, and create commodity objects using different product structures through the subdivision level under the product structure;

    * The specific product factory class depends on the specific factory for product family product creation;

2. Code Analysis

    * Abstract factory class

public abstract class AbstractFactory {

    public abstract Milk createMengNiuMilk();

    public abstract Milk createYiLiMilk();

    public abstract Milk createTeLunSuMilk();
}

    * Specific factory class

public class ShanXiProxyFactory extends AbstractFactory {
    @Override
    public Milk createMengNiuMilk() {
        return new MengNiuFactory().createMilk();
    }

    @Override
    public Milk createYiLiMilk() {
        return new YiLiFactory (). createMilk ();
    }

    @Override
    public Milk createTeLunSuMilk() {
        return new TeLunSuFactory().createMilk();
    }
}
public class BeiJingProxyFactory extends AbstractFactory {
    @Override
    public Milk createMengNiuMilk() {
        return new MengNiuFactory().createMilk();
    }

    @Override
    public Milk createYiLiMilk() {
        return new YiLiFactory (). createMilk ();
    }

    @Override
    public Milk createTeLunSuMilk() {
        return new TeLunSuFactory().createMilk();
    }
}

    * The product category and product factory category are the same as above, and the product structure category is not subdivided for the product factory category

    * test class

public class AbstractFactoryClass {
    public static void main(String[] args) {
        AbstractFactory factory = new ShanXiProxyFactory();
        Milk milk = factory.createMengNiuMilk();
        System.out.println(milk.getName());
    }
}

3. Analysis of advantages and disadvantages

    * Abstract factory mode, which proposes the concept of product family, integrates product behaviors under the same module, and is conducive to modular business model processing;

    * Unreasonable application of abstract factory pattern can easily lead to class structure explosion;

Fourth, case analysis:

    To give a simple example, if a little brother graduated from college and started a business, he started a fried chicken chop shop. Because the initial investment was too small, there was only a small shop of about a few square meters. The small shop sells fried chicken chop, barbecue. There are also fruit juice milk tea, and the little brother is only busy with himself;

    In this way, every time a customer comes and puts forward his own needs, the little brother needs to provide the products that the customers need according to the needs of each customer. Slowly, the small shop has good opinions. The small shop has introduced other products such as ice cream, and the little brother is getting more and more The more you can't do it, the more you need to recruit a clerk. (Simple Factory Pattern)

    The little brother recruited several clerks and asked each clerk to be responsible for the production of each product, so that the small shop had a clerk specializing in juice milk tea, and a little brother specializing in fried chicken chops. . . , After a period of time, the little brother's store became bigger and bigger, and he became more and more famous, and slowly attracted the little brothers from other places to seek to join. (factory method pattern)

    Although there is not much difference in products between the franchisee's store and the original store of the younger brother, there are also subtle differences in the selection of materials and production processes. In this way, the little brother has determined the basic commodities in the store, and each franchisee can make appropriate expansion of commodities and independent selection of product processing according to local conditions. Each franchisee store forms a different product structure from other stores. (Abstract Factory Pattern)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325849380&siteId=291194637