Factory Pattern – Factory method pattern


Become as

Hello everyone, I am silent. In this class, we will talk about the factory mode based on the demand of pizza ordering. The second mode is factory method mode

Antecedents feed

First of all, we raised this requirement last time

There is a demand for such a pizzeria with a wide variety of pizzas (GreekPizz, CheesePizz, etc.)

Prepare, bake, cut, box, etc

Requirements: Complete the pizza shop order function, easy to expand the pizza variety, easy to maintain

With this requirement in mind, last time we used the simple Factory pattern to refactor the code to complete the function of ordering pizza. At the same time, we also made it clear that in the simple Factory pattern, the factory class is responsible for encapsulating the details of instantiating objects, which is used when it comes to creating a large number of objects or classes

Case Extension – Offsite delivery

OK, now the pizza project is becoming bigger and stronger. Let’s take a look at the new requirements of the pizza project. Now customers can order pizza in different cities when ordering pizza, such as Cheese Pizza and fruit Pizza in Beijing or Cheese Pizza and fruit Pizza in Shanghai

Case analysis

In this case, we can use the simple factory mode. We can create different simple factory classes, such as BJSimpleFactory for Beijing pizza, SHSimpleFactory for Shanghai pizza. In terms of single current such demand, is also no problem, but we consider that is a lot of place, if every site needs a factory class to maintain, certainly will will cause the factory class too much behind, the maintainability and extensibility of the whole system is not high, so, we have introduced a second, factory method pattern

Let’s start with a basic introduction to the factory method pattern

Basic introduction – Factory method pattern

Factory method pattern: Defines an abstract method for creating objects, with subclasses deciding which classes to instantiate

The core idea of the factory method pattern is to defer object instantiation to subclasses


Factory method pattern of simple Factory pattern in the abstract, is an abstract Factory class (abstract class or interface), the class will no longer be responsible for the specific product, but only for some specifications, specific production work completed by its subclasses to, in this pattern, Factory and product class often can, in turn, the corresponding, A specific factory corresponds to a specific product, and the specific factory is responsible for producing the corresponding product

Improvement ideas

According to the factory method pattern described above, we can use the factory method pattern to improve the case, the pizza project instantiation function is abstracted into an abstract method (the original SimpleFactory createPizza() method) to order pizza at different locations, by its subclass concrete implementation

Solution 3 – Factory approach pattern

Then we use the factory mode for coding. First, we define the entity class of pizza in each location and put together the basic architecture first. The relevant class diagram is as follows



The corresponding code is shown in the following figure

// Pizza abstract class
public abstract class Pizza {

    // Define an attribute, the name of the pizza, and give the set method
    protected String name;

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

    public String getName(a) {
        return name;
    }

    // Different pizzas are prepared with different ingredients, so they are defined as abstract methods
    public abstract void prepare(a);

    // Baking method
    public void bake(a) {

        System.out.println(name + "It's baking.");
    }

    // Cutting method
    public void cut(a) {

        System.out.println(name + "About to cut the pizza into pieces.");
    }

    // Package method
    public void box(a) {

        System.out.println(name + "Wrap pizza for customers."); }}// Fruit pizza in Beijing
public class BJFruitPizza extends Pizza {

    @Override
    public void prepare(a) {

        setName("Fruit Pizza in Beijing");
        System.out.println("Raw materials are being prepared for Fruit pizza in Beijing."); }}// Greek pizza in Beijing
public class BJGreekPizza extends Pizza {

    @Override
    public void prepare(a) {

        setName("Greek Pizza in Beijing");
        System.out.println("Beijing's Greek pizza is preparing its ingredients."); }}// Fruit pizza in Shanghai
public class SHFruitPizza extends Pizza {

    @Override
    public void prepare(a) {

        setName("Fruit Pizza in Shanghai");
        System.out.println("Shanghai's fruit Pizza is preparing its ingredients."); }}// Greek pizza in Shanghai
public class SHGreekPizza extends Pizza {

    @Override
    public void prepare(a) {

        setName("Greek Pizza in Shanghai");
        System.out.println("Shanghai's Greek pizza is preparing its ingredients."); }}Copy the code

Again, we need to define the OrderPizza class OrderPizza, but in a different way, we make it an abstract class that acts as the abstract factory class in the factory method pattern. In this class, we define the abstract method createPizza(), which also gets the type of pizza the customer wants to order. At the same time, we define two subclasses of OrderPizza, which are responsible for ordering pizza in Shanghai and Beijing respectively. The related class diagram is shown as follows

Shown below



The corresponding code is shown in the following figure

// Order pizza
public abstract class OrderPizza {

    // Abstract factory class - make specification
    abstract Pizza createPizza(String orderType);

    public OrderPizza(a){

        Pizza pizza = null;

        String orderType = "";

        while (true){

            orderType = getType();

            pizza = createPizza(orderType); // Abstract method, done by factory subclass

            pizza.prepare(); // Output the Pizza making processpizza.bake(); pizza.cut(); pizza.box(); }}// Define methods to get the type of pizza a customer wants to order
    private String getType(a){

        System.out.println("What kind of Pizza would you like to order?");

        Scanner scanner = new Scanner(System.in);

        String str = scanner.next();

        returnstr; }}// Beijing order class
public class BJOrderPizza extends OrderPizza {

    @Override
    Pizza createPizza(String orderType) {

        Pizza pizza = null;

        if (orderType.equals("GreekPizza")){

            pizza = new BJGreekPizza();

        }else if (orderType.equals("FruitPizza")){

            pizza = new BJFruitPizza();
        }
        returnpizza; }}// Order from Shanghai
public class SHOrderPizza extends OrderPizza {


    @Override
    Pizza createPizza(String orderType) {

        Pizza pizza = null;

        if (orderType.equals("GreekPizza")){

            pizza = new SHGreekPizza();

        }else if (orderType.equals("FruitPizza")){

            pizza = new SHFruitPizza();
        }
        returnpizza; }}// Pizza store client
public class PizzaStore {

    public static void main(String[] args) {

        System.out.println("Please enter the place to order pizza.");

        String address = new Scanner(System.in).next();

        if (address.equals("Beijing")) {new BJOrderPizza();

        }else if (address.equals("Shanghai")) {new SHOrderPizza();

        }else{
            System.out.println("Pizza ordering is not available at this location."); }}}Copy the code

Project analysis

OK, above we use the factory method mode to complete the code reconstruction, first to ensure that the demand for ordering pizza runs normally, the running result is shown in the figure below



Therefore, the factory method pattern is a derivative of the simple factory pattern, which solves many problems of the simple factory pattern. First, it fully conforms to the open and closed principle, which can be extended. Second, it has a more complex hierarchical structure, which can be applied to the occasion of complex product results

Next day forecast

OK, as a result of the limitation of space, this section will first come here, in the next section, we went on to talk to the factory model of the third, the abstract factory pattern, and the application of the factory pattern in the JDK source code, the factory pattern considerations and summary, finally, hope everyone in the process of learning, can feel interesting about design patterns, efficient and pleasant learning, I’ll see you next time