The three realizations of factory mode are so simple!

Factory mode

Factory pattern is a common design pattern in development. Each design pattern will greatly solve the problem of program design. The same is true for factory pattern. This paper will explain what is factory pattern with popular language? Types of factory patterns, code examples, advantages and disadvantages of each factory pattern, and applicable scenarios of factory patterns.

Why use factory mode?

First of all, we use a vivid story to describe what is the factory mode, which will make you understand the factory mode faster and lay the foundation for the following understanding of several implementation methods of the factory mode.

If, you need to let a company open an income proof to offer income proof for oneself loan to buy a house, the process that opens income proof commonly is:

  1. Print the income certificate;
  2. Stamp the company's seal on the income certificate;

Throughout the process, you know that you need to create an income certificate and use it to provide information for a loan to buy a house. In this process, there are two key behaviors: creating revenue proof and using revenue proof. There are two steps in the process of establishing income certificate: printing and stamping. When colleagues who are not familiar with this process are creating income certificates, they often encounter many troubles, which leads to frequent obstacles in opening income certificates. Therefore, the company decides to optimize the issue of opening income certificates for employees. What used to need to be done in two steps is to send only one email to the financial department, and the financial department will send the sealed income certificates to the work station before leaving work This is the factory model we meet in our life.

Having said so much, what problems in life have factory model solved?

In this life case, it makes it easier for employees to create income certificates. Employees don't need to know how to create income certificates. They just need to send an email to the financial department, which will help employees print and stamp. And in the follow-up development of the company, if more seals are needed in the income certificate, employees do not need to get familiar with the whole process, take the income certificate to all departments to stamp.

So, in the world of programs, how to use code to demonstrate that employees buy houses for loans and go to the company to prove this behavior? How to show the factory pattern with code?

Similar to the above example, if there is a revenue proof class that only needs a new click, the input parameter is to print the proof and seal the proof. If the seal of the subsequent revenue proof changes, the input parameter needs to be modified. This requires a large number of new code calls to create revenue proof classes.

Then the factory mode can be used. The factory mode separates the creation of A class from the use of A class. When Class A wants to call Class B, then Class A just calls the method of Class B. as for the instantiation of Class B, it is handed to the factory class.

It's also said that you can also put the code of the creation process into the constructor of the class, which can also reduce the repetition rate, and the function of the constructor itself is to initialize the object. For this point of view, we can compare the advantages of factory mode with that of constructor:

Advantage:

  1. Static factory methods have names but constructors don't, because factory methods can have multiple names to distinguish each method, but constructor names can only have one name and can only be distinguished by parameters, so using static factory methods is clearer.

  2. The static factory method supports conditional instantiation, that is, when you create an object, sometimes you need to add some conditions to determine whether it should be created. If the conditions are met, an instance will be returned. If not, NULL will be returned, such as the single instance mode. Constructors cannot do this. The function of constructors needs to be single and exist only for construction, while static factory methods can be very simple.

  3. Method can return a subtype of the return type

This is the advantages of factory pattern in creating objects. The core knowledge of factory pattern is to separate the creation and use of objects. Please meditate three times.

It's much easier to grasp the core point and then understand the various implementations of the factory mode. The factory mode can be generally divided into three types:

  • Simple / static factory mode
  • Factory method mode
  • Abstract factory pattern

Our learning steps are as follows: factory method mode to simple static factory mode to abstract factory mode. The examples are very simple. You can understand the code at a glance. Students who are interested in github can download the code:

github address: Java 23 design pattern code examples factory pattern

I know that all of you are caring people. Of course, it's not your habit to whore in vain. Welcome to have a series of three qualities: concern, praise and star

Factory method mode

The factory method is relatively simple and simple \ the static factory is relatively simple and easy to understand.

If we need to build a mobile phone in the factory, we need to define a phone abstract class first. The mobile phone must have the function of making a call and add a call abstract method

package com.shuai.design.factory.normals;

public abstract class Phone {

    // All mobile phones must have the function of calling
    public abstract void call();

}

To create a factory interface of a mobile phone, there is a createPhone method. Other types of mobile phones need to inherit this interface. To create a mobile phone, this method must be implemented

package com.shuai.design.factory.normals;

import com.shuai.design.factory.simples.Phone;

public interface PhoneFactory {

    Phone createPhone();
}

Create Xiaomi mobile class. Inherit phone and implement call method

package com.shuai.design.factory.normals;

import com.shuai.design.factory.simples.Phone;

public class MiPhone extends Phone {

    @Override
    public void call() {
        System.out.println("this is MI call");
    }
}

Create Xiaomi mobile phone factory

package com.shuai.design.factory.normals;

public class MiPhoneFactory implements PhoneFactory {

    @Override
    public MiPhone createPhone() {
        return new MiPhone();
    }
}

Similar to Xiaomi mobile phone, Huawei mobile phone class is implemented, inheriting the phone abstract class and implementing the call method

package com.shuai.design.factory.normals;

import com.shuai.design.factory.simples.Phone;

public class HuaWeiPhone extends Phone {

    @Override
    public void call() {
        System.out.println("this is HuaWei Phone");
    }
}

Huawei mobile phone factory

package com.shuai.design.factory.normals;

public class HuaWeiPhoneFactory implements PhoneFactory{

    @Override
    public HuaWeiPhone createPhone() {
        return new HuaWeiPhone();
    }
}

Simple static factory mode

Static factory is much simpler than factory method pattern. First, create an abstract class of phone

package com.shuai.design.factory.simples;

public abstract class Phone {

    // All mobile phones must have the function of calling
    public abstract void call();

}

Then create the building factory class of the phone, and create different types of mobile phones according to the incoming type

package com.shuai.design.factory.simples;

public class PhoneFactory {

    public static MiPhone createMiPhone() {
        return new MiPhone();
    }

    public static HuaWeiPhone createHuaWeiPhone() {
        return new HuaWeiPhone();
    }

    public static Phone createPhone(String type) {
        if ("Mi".equals(type)) {
            return new MiPhone();
        } else {
            return new HuaWeiPhone();
        }
    }
}

Realize Xiaomi Mobile

package com.shuai.design.factory.simples;

public class MiPhone extends Phone {

    @Override
    public void call() {
        System.out.println("this is MI call");
    }
}

Huawei Mobile

package com.shuai.design.factory.simples;

public class HuaWeiPhone extends Phone {

    @Override
    public void call() {
        System.out.println("this is HuaWei Phone");
    }
}

Abstract factory pattern

Definition: provides an interface for creating a set of related or interdependent objects without specifying their concrete classes

The picture shows:

Here, we use the way of creating mobile phones to realize the abstract factory. First, we create an abstract class of mobile phones, which includes not only the call method, but also the screen type of mobile phones

package com.shuai.design.factory.abstracts;

public abstract class Phone {

    // All mobile phones must have the function of calling
    public abstract void call();

    // Screen type of mobile phone
    public abstract void screenType();

}

Create another parent interface of mobile building factory

package com.shuai.design.factory.abstracts;

public interface PhoneFactory {

    Phone createMiPhone();

    Phone createHuaWeiPhone();

}

First of all, all Xiaomi mobile phones and Huawei mobile phones must realize the call function and rewrite the call method

package com.shuai.design.factory.abstracts;


public abstract class MiPhone extends Phone {

    @Override
    public void call() {
        System.out.println("this is MI call");
    }

}

package com.shuai.design.factory.abstracts;


public abstract class HuaWeiPhone extends Phone {

    @Override
    public void call() {
        System.out.println("this is HuaWei Phone");
    }

}

According to the screen type of mobile phone, it can be divided into Xiaomi folding screen mobile phone:

package com.shuai.design.factory.abstracts;

public class FoldingScreenMiPhone extends MiPhone {

    @Override
    public void screenType() {
        System.out.println("this is Xiaomi folding screen mobile phone");
    }

}

According to the screen type of the mobile phone, it can be divided into Huawei folding screen mobile phones:

package com.shuai.design.factory.abstracts;

public class FoldingScreenHuaWeiPhone extends HuaWeiPhone {

    @Override
    public void screenType() {
        System.out.println("this is Huawei folding screen mobile phone");
    }

}

According to the screen type of mobile phone, it can be divided into millet curved screen mobile phone:

package com.shuai.design.factory.abstracts;

public class CurvedScreenMiPhone extends MiPhone {

    @Override
    public void screenType() {
        System.out.println("this is Xiaomi curved screen mobile phone");
    }
}

According to the screen type of the mobile phone, it can be divided into Huawei curved screen mobile phones:

package com.shuai.design.factory.abstracts;

public class CurvedScreenHuaWeiPhone extends HuaWeiPhone{

    @Override
    public void screenType(){
        System.out.println("this is Huawei curved screen mobile phone");

    }

}

According to different screen types of mobile phones, it abstracts the construction factories according to screen types, including curved screen mobile phone factory and folding screen mobile phone factory

package com.shuai.design.factory.abstracts;
//Curved screen mobile phone factory
public class CurvedScreenPhoneFactory implements PhoneFactory {

    @Override
    public CurvedScreenMiPhone createMiPhone() {
        return new CurvedScreenMiPhone();
    }

    @Override
    public CurvedScreenHuaWeiPhone createHuaWeiPhone() {
        return new CurvedScreenHuaWeiPhone();
    }
}

Folding screen mobile phone factory

package com.shuai.design.factory.abstracts;
//Folding screen mobile phone factory
public class FoldingScreenPhoneFactory implements PhoneFactory{

    @Override
    public FoldingScreenMiPhone createMiPhone() {
        return new FoldingScreenMiPhone();
    }

    @Override
    public FoldingScreenHuaWeiPhone createHuaWeiPhone() {
        return new FoldingScreenHuaWeiPhone();
    }

}

Write another test class to test the following results:

package com.shuai.design.factory.abstracts;

public class Test {

    public static void main(String[] args) {

        // Create a Huawei curved screen mobile phone
        CurvedScreenHuaWeiPhone curvedScreenHuaWeiPhone = new CurvedScreenPhoneFactory().createHuaWeiPhone();
        System.out.println("curvedScreenHuaWeiPhone The phone types of are:");
        curvedScreenHuaWeiPhone.screenType();

        // Create a Xiaomi curved screen mobile phone
        CurvedScreenMiPhone curvedScreenMiPhone = new CurvedScreenPhoneFactory().createMiPhone();
        System.out.println("curvedScreenMiPhone The phone types of are:");
        curvedScreenMiPhone.screenType();

        // Create a Huawei folding screen mobile phone
        FoldingScreenHuaWeiPhone foldingScreenHuaWeiPhone = new FoldingScreenPhoneFactory().createHuaWeiPhone();
        System.out.println("foldingScreenHuaWeiPhone The phone types of are:");
        foldingScreenHuaWeiPhone.screenType();

        // Create a millet folding screen mobile phone
        FoldingScreenMiPhone foldingScreenMiPhone = new FoldingScreenPhoneFactory().createMiPhone();
        System.out.println("foldingScreenMiPhone The phone types of are:");
        foldingScreenMiPhone.screenType();

    }

}

Usage scenario of abstract factory pattern: if an object family (or a group of unrelated objects) has the same constraints, you can use abstract factory pattern. Through the factory class, as long as I know who the factory class is, I can create a required object

Disadvantages:

It's difficult to expand the product family. For example, if a mobile phone with stylus type is added to the phone type, each implemented mobile phone class needs to implement this method. This is a serious violation of the opening and closing principle.

Advantage:

It's easy to increase the level. If you add a mobile phone with two or three fold screens under the fold screen mobile phone, it is relatively simple. You only need to modify it under the fold screen mobile phone construction factory.

summary

In fact, in the general development process, we use a lot of simple factory patterns, and abstract factory patterns need to be used when the business is relatively large. If you have a better point of view, please come up with it in the comment area and learn from each other.

reference material:

Tags: Programming Mobile github Java

Posted on Mon, 23 Mar 2020 23:03:35 -0400 by poe