One, the introduction

1. What is factory mode?

The factory model is like a milk tea shop. If you need anything, tell him and they will make it for you instead of making it by themselves. For example, when Lao Wang wants an Audi, he has two choices: one is to build it by himself (called new in Java), the other is to tell the 4S shop (factory), and then pay the money to pick up the car and leave. The second is the factory model, where you tell people what you need and they build it for you.

2. What’s the use?

Factory mode is intended to decouple, which is to reduce the close relationship between each module in the program module, and achieve low coupling, making the code more convenient and easy to maintain.

3. How?

How do you do that? Like the singleton pattern, the factory pattern can be implemented in three ways:

  • Simple factory
  • The factory method
  • The abstract factory

The following is a description of these implementation methods.

Second, to achieve the factory model

1. Simple factories

Go straight to the class diagram:The class diagram is clear and easy to understand. Audi, Mercedes and BMW implement an interface called Car. A factory depends on all three kinds of cars.

Here is the implementation code: Here are the Car, interface and Audi, BMW, Mercedes implementation classes

/ / Car interface
public interface Car {}/ / the audi
class Audi implements Car{}/ / BMW
class BMW implements Car{}/ / Benz
class Benz implements Car{}Copy the code

Below is the car factory and the Main method

// Car factory
public class CarFactory {
    // How to get a car
    public static Car getCar(String name){
        if (name.equals("Audi")) {return new Audi();
        }
        if (name.equals("BMW")) {return new BMW();
        }
        if (name.equals("Mercedes")) {return new Benz();
        }else {
            return null; }}/ / the Main method
    public static void main(String[] args) {
    	// Tell the factory what kind of car you want and it will make you that carCar = carfactory.getCar ("Audi"); Car = carfactory.getCar ("BMW"); Car = carfactory.getCar ("Mercedes"); }}Copy the code

Basically the getCar() method in the car factory, you send it an Audi, it makes an Audi, send it a BMW, it makes a BMW. That’s the simple factory pattern, and it should be easy to understand and simple by this point.

However, such factories have a small problem: they do not abide by the open and closed principle and forget the point here, which is in violation of the expansion and opening of the supplier, and the modification and closing of the user. For example: Lao Wang suddenly rich, want to buy a Rolls-Royce, this time tell the car factory, car factory how to do? Is bound to modify the source code, modified as follows:

// Rolls Royce
class RollsRoyce implements Car{}Copy the code

In order to expand the model, there is no problem to add Rolls-Royce class, but look at the following:

// How to get a car
public static Car getCar(String name){
    if (name.equals("Audi")) {return new Audi();
    }
    if (name.equals("BMW")) {return new BMW();
    }
    if (name.equals("Mercedes")) {return new Benz();
    }if (name.equals(Rolls Royce)) {return new RollsRoyce();
    }
    else {
        return null; }}Copy the code

We added an if condition, which was problematic, seriously violated the open and close principle and modified the original code, so we proposed a second factory: the factory method pattern

2. Factory method

The factory method mode can add models arbitrarily, and does not need to modify the original code each time, and follows the open and closed principle. The class diagram is as follows:It should have seemed simple enough to split up what was once a plant, and nowEach factory implements the factory interfaceandOnly responsible for the production of its corresponding cars (Audi factory produces Audi cars)Now if Wang wanted a Bentley, he could just build a new Bentley factory to implement the auto factory interface, and never modify the original code. The implementation code is as follows:

// Auto factory interface
public interface CarFacory {
    public Car getCar(a);
}

// Audi factory
class AudiFactory implements CarFacory{
    public Car getCar(a) {
        return newAudi(); }}// BMW factory
class BMWFactory implements CarFacory{

    public Car getCar(a) {
        return newBMW(); }}// Mercedes-benz factory
class BenzFactory implements CarFacory{
    public Car getCar(a) {
        return newBenz(); }}// Miss Rice factory
class RollsRoyceFactory implements CarFacory{
    public Car getCar(a) {
        return newRollsRoyce(); }}Copy the code

Here are the various models:

/ / Car interface
public interface Car {}/ / the audi
class Audi implements Car {}/ / BMW
class BMW implements Car {}/ / Benz
class Benz implements Car {}// Rolls Royce
class RollsRoyce implements Car {}Copy the code

It can be seen from the above that the factory method mode can well solve the work of modifying the original code when adding models.

But the trouble comes again. Due to the severity of the epidemic, major factories are preparing to produce masks to meet the market demand. Now factories are not only producing cars, but also masks. This factory method is obviously not working, so the first abstract factory.

3. Abstract Factory (difficult to understand)

As usual, go straight to the class diagram: Each factory inherits an abstract class (Abstract factory)There are two methods getCar and getMask. thenEach factory relies on its own brand of cars and masks, for example: Audi factory contains Audi cars and Audi masks; BMW factory contains BMW cars and BMW masks.

The implementation code is as follows:

Here’s the car category:

/ / Car interface
public interface Car {}/ / the audi
class Audi implements Car {}/ / BMW
class BMW implements Car {}/ / Benz
class Benz implements Car {}Copy the code

Here are the mask categories:

// Mask interface
public interface Mark {}// Audi mask
class AudiMark implements Mark{}// BMW mask
class BMWMark implements Mark{}// Mask
class BenzMark implements Mark{}Copy the code

Here’s the factory:

// Abstract factory
public abstract class AbsFactory {
    public abstract Car getCar(a);
    public abstract Mark getMark(a);
}

// Audi factory
class AudiFactory extends AbsFactory{
    public Car getCar(a) {
        return new Audi();
    }
    public Mark getMark(a) {
        return newAudiMark(); }}// BMW factory
class BMWFactory extends AbsFactory{
    public Car getCar(a) {
        return new BMW();
    }
    public Mark getMark(a) {
        return newBMWMark(); }}// Mercedes-benz factory
class BenzFactory extends AbsFactory{

    public Car getCar(a) {
        return new Benz();
    }
    public Mark getMark(a) {
        return newBenzMark(); }}Copy the code

Third, summary

There are no good or bad factory implementation modes, the most commonly used is simple factory, factory method and abstract factory should be used separately from the actual situation. Generally speaking, factory mode is a relatively simple mode, as long as you write code, draw class diagrams, you can understand. Really don’t understand can see video teaching: crazy god teacher’s factory method crazy God teacher’s abstract factory