4 - Design Mode - simple factory mode

Posted by GoodWill on Sat, 26 Feb 2022 15:07:30 +0100

1, What is a simple factory

1) Simple factory mode belongs to the creation mode, which is a kind of factory mode. The simple factory pattern is that a factory object determines which product class instance to create. Simple factory model is the simplest and most practical model in the factory model family

2) Simple factory pattern: defines a class for creating objects, which encapsulates the behavior (code) of instantiating objects

3) In software development, when we will use a lot of to create a, a class or a batch of objects, we will use the factory mode.

2, Specific examples

A pizza project: to facilitate the expansion of pizza types and maintenance

1) There are many kinds of pizza (such as: greenpizza, CheesePizz, etc.)

2) Pizza making includes prepare, bake, cut and box

3) Complete the pizza shop ordering function.

UML diagram

Traditional way

/**
 * Pizza base
 * @author Jason
 */
public abstract class Pizza {

    protected String name;

    /**
     * Preparation, subclass specific implementation
     */
    public abstract void prepare();

    /**
     * baking
     */
    public void bake() {
        System.out.println(name + "baking");
    }

    /**
     * cutting
     */
    public void cut() {
        System.out.println(name + "cutting");
    }

    /**
     * pack
     */
    public void box() {
        System.out.println(name + "pack");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

/**
 * @author Jason
 */
public class GreekPizza extends Pizza{

    @Override
    public void prepare() {
        System.out.println("Prepare materials for Greek pizza ");
    }
}

/**
 * @author Jason
 */
public class CheesePizza extends Pizza{

    @Override
    public void prepare() {
        System.out.println("Prepare ingredients for cheese pizza");
    }
}

public class OrderPizza {


    // constructor 
    public OrderPizza() {
        Pizza pizza = null;
        String orderType;   // Type of pizza ordered
        do {
            orderType = getType();
            if (orderType.equals("greek")) {
                pizza = new GreekPizza();
                pizza.setName("Greek pizza");
            } else if (orderType.equals("cheese")) {
                pizza = new CheesePizza();
                pizza.setName("Cheese pizza");
            } else {
                break;
            }
            // Output pizza production process
            pizza.prepare();
            pizza.bake();
            pizza.cut();
            pizza.box();
        } while (true);
    }

    /**
     *  Write a method to get the type of pizza customers want to order
     * @return
     */
    private String getType() {
        try {
            BufferedReader string = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("input pizza type:");
            String str = string.readLine();
            return str;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
public class PizzaStore {

    public static void main(String[] args) {
        new OrderPizza();
    }
}

Advantages and disadvantages of traditional methods:

1) The advantage is that it is easy to understand and operate

2) The disadvantage is that it violates the ocp principle of design pattern, that is, it is open to extension and closed to modification. That is, when we add new functions to the class, we try not to modify the code or modify the code as little as possible.

3) For example, we need to add a new type of Pizza (Pepper Pizza) and judge the type of Pepper Pizza

Analysis of improvement ideas
Analysis: it is acceptable to modify the code, but if we also have the code to create Pizza in other places, it means that we also need to modify it, and there are often many codes to create Pizza.

Idea: encapsulate the creation of Pizza objects into a class, so that when we have a new Pizza type, we only need to modify the class, and other codes that create Pizza objects do not need to be modified.

Simple factory mode

Create factory class simpefactorypizza (defines a class for creating objects, which encapsulates the behavior of instantiated objects)

public class SimpleFactoryPizza {

    public Pizza createPizza(String orderType){
        Pizza pizza = null;
        System.out.println(" Use simple factory mode ");
        if (orderType.equals("greek")) {
            pizza = new GreekPizza();
            pizza.setName("Greek pizza");
        } else if (orderType.equals("cheese")) {
            pizza = new CheesePizza();
            pizza.setName("Cheese pizza");
        }
        return pizza;
    }
}

Modify OrderPizza class

public class OrderPizza {

    SimpleFactoryPizza simpleFactoryPizza;
    Pizza pizza = null;

    // Modify constructor
    OrderPizza(SimpleFactoryPizza simpleFactoryPizza) {
        setSimpleFactory(simpleFactoryPizza);
    }

    private void setSimpleFactory(SimpleFactoryPizza simpleFactoryPizza) {
        String orderType;   // Type of pizza ordered
        this.simpleFactoryPizza = simpleFactoryPizza;
        do {
            orderType = getType();
            //The pizza class is created by the factory class, so if there is a new pizza, only the factory class can be modified
            pizza = simpleFactoryPizza.createPizza(orderType);
            if (pizza != null) {
                // Output pizza production process
                pizza.prepare();
                pizza.bake();
                pizza.cut();
                pizza.box();
            } else {
                System.out.println(" Pizza making failed ");
            }

        } while (true);
    }


    /**
     * Write a method to get the type of pizza customers want to order
     *
     * @return
     */
    private String getType() {
        try {
            BufferedReader string = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("input pizza type:");
            String str = string.readLine();
            return str;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}

Topics: Java Design Pattern