Mi author: Qian Jue

Email address: [email protected]

Official account: Qian Jue (Jue)

Title: Factory Patterns of Design Patterns

Hello, gentlemen, I am back to update, I believe that the previous article readers should be familiar with the singleton pattern. Originally wanted to write more design patterns a day, but because of the recent liver chicken Leo did not have time to write, ho ho, this is really a very good pigeon reason.

Thousand Jue this chapter will take you to see the factory pattern, based on the principle of from easy to complex, so is preferred to introduce this mode, it is the second good thousand Jue think understanding of design patterns, it is because of too simple, so how can not speak out vividly, after all, the more simple the more difficult it is to speak, I as far as possible according to the example of life to cooperate.

Factory mode classification

  • Simple Factory model
  • Factory method pattern
  • Abstract Factory pattern

What is the Simple Factory pattern

define

The simple factory pattern belongs to the creation pattern also known as the static factory method pattern, which belongs to the class creation pattern. In the simple factory pattern, you can return instances of different classes depending on the parameters. The simple factory pattern specifically defines a class that is responsible for creating instances of other classes, which usually have a common parent class

One of the most important words in the definition is to define a target class that is responsible for creating instances of other classes.

Like when my cousin goes for a job interview

Cousin: Hello, I’m cousin.

Interviewer: Hello, Qian – chueh, can you write a simple calculator in code?

Cousin: Sure. (Inner OS: Clam, the interviewer is so contemptible of me.)

Then She gave the following code.

public class Calculator{
    public static void main(String []args){
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the number A");
        double a = scan.nextDouble();
        System.out.println("Please enter data B");
        double b = scan.nextDouble();
        System.out.println("Please enter operation symbol + - * /");
        String operator = scan.next();
        double result = 0;
        if(operator.equals("+")){
            result = a + b;
        }else if(operator.equals("-")){
            result = a - b;
        }else if(operator.equals("*")){
            result = a * b;
        }else if(operator.equals("/")) {if(b == 0){
               System.out.println("The dividend b can't be zero. There's an error.");
               System.exit(0);
            }else{ result = a / b; }}else{
            System.out.println("The result is wrong");
            System.exit(0);
        }
        System.out.println(a + "+"  + operator + "" + b + "="+ result ); }}Copy the code

After writing the code above and showing it to the interviewer.

Cousin: Interviewer, you can see that this program has realized the function of a simple calculator.

The interviewer; Well, it’s all right but it’s still a little short, so go home and wait.

Cousin above the code to write although the function is realized, but there is no way to reuse this program, if I want to add an open root operation function, it is about to change the above code, so I if the interviewer I certainly don’t let cousin through.

The interviewer actually wants to test the cousin is the factory model, let qianjue take you to see, the interviewer wants to see the code, I hope all of you don’t make the same mistake as my cousin when going to the interview.

// Operation method interface
public interface IOperation{
    public double operation(double a, double b);
}
// A concrete operation class
public class OperationAdd implements IOperation{
    public double operation(double a,double b){
        returna + b; }}public class OperationSub implements IOperation{
    public double operation(double a,double b){
        returna - b; }}public class OperationMul implements IOperation{
    public double operation(double a,double b){
        returna * b; }}public class OperationDiv implements IOperation{
    public double operation(double a,double b){
        if(b == 0) {throws Exception("The dividend cannot be zero.");
        }
        returna / b; }}/ / the factory class
public class OperationFactory{
    private OperationFactory{}
    public static IOperation createrOperation(String name){
        if(name == null) {return null;
        }
        if(name.equals("+")) {return new OperationAdd();
        }else if(name.equals("-")) {return new OperationSub();
        }else if(name.equals("*")) {return new OperationMul();
        }else if(name.equals("/")) {return new OperationDiv();
        }else{
            return null; }}}/ / test class
public class TestOperation{
    public static void main(String []args){
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the number A");
        double a = scan.nextDouble();
        System.out.println("Please enter data B");
        double b = scan.nextDouble();
        System.out.println("Please enter operation symbol + - * /");
        String oper = scan.nextLine();
        IOperation operation = OperationFactory.createOperation();
        System.out.println(a + ""  + oper + "" + b + "="+ operation.operation(a,b)); }}Copy the code

If you want to write the above simple factory pattern you have the essence of the above code, if you want to change the logic of the addition, you can change it directly in the method of the addition class, you don’t have to change the main code program, perfect decoupling. If you want to add another operator, you can add a subclass of the operator, add a decision branch in the factory, but there are some problems with this model, and I’ll explain the problem.

What is the factory Method pattern

define

Define an interface for creating objects and let subclasses decide which class to instantiate. The factory then delays the instantiation of a class to its subclasses.

Let’s rewrite the above example using the factory method

// Factory method interface
public interface OperationFactory{
  IOperation createrOperation(a);   
}
// Specific factory
public class AddFactory implements OperationFactory{
    public IOperation createrOperation(a){
        return newOperationAdd(); }}public class SubFactory implements OperationFactory{
    public IOperation createrOperation(a){
        return newOperationSub(); }}public class MulFactory implements OperationFactory{
    public IOperation createrOperation(a){
        return newOperationMul(); }}public class DivFactory implements OperationFactory{
    public IOperation createrOperation(a){
        return newOperationDiv(); }}/ / test class
public class TestOperation{
    public static void main(String []args){
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the number A");
        double a = scan.nextDouble();
        System.out.println("Please enter data B");
        double b = scan.nextDouble();
        OperationFactory operationFactory = new AddFactory();
        IOperation operation = operationFactory.createrOperation();
        System.out.println(a + "+" + b + "="+ operation.operation(a,b)); }}Copy the code

See here believe that some see officials will ask thousand jue.

Look at the officials: Thousand Jue, simple factory pattern before me if you want to add a new operation method, I just add a function class, go to the factory method to add a branch of judgment not to go, but now with the factory method, to add a class function, but also add a related factory class, but also to change the client, this is not increased a lot of classes and methods, adds complexity, Why don’t we just go with the simple factory model?

Qian chueh: The officials looked at this question very carefully. This is exactly the difference between the simple factory model and the factory method model. Before if we want to add a new operator method, we are factory must modify the computation method in a class can modify the original class, so we not only open for extension, open to changes, so that it violates the principle of open and close, so this time the factory method becomes, solves the above problem of simple factory.

If you look at the officials carefully, you will find that Qian Chueh said in the above, although the simple factory model is good, but there are some problems, yes, it is against the open and closed principle, and the factory method model is easy to solve the problem of the simple factory model.

What is the Abstract Factory pattern

define

Provides an interface for creating a series of related or interdependent objects without specifying their concrete classes.

If you look at this definition and you get confused, look at the following example and you’ll see that the abstract factory pattern isn’t that hard after all.

For example, we are Xiaomi company, now we want to produce mobile phones, microwave ovens, air conditioners.

This is the code that we’re going to write at this point

// Phone port
public interface Phone{
    String createPhone(a);
}
// Microwave port
public interface Micro{
    String createMircro(a);
}
// Air conditioner interface
public interface Aircond{
    String createAircond(a);
}
// Specific product category
public XiaomiPhone implements Phone{
    public String createPhone(a){
        return "Xiaomi Phone"; }}public XiaomiMicro implements Micro{
    public String createMircro(a){
        return Millet Microwave oven; }}public XiaomiAircond implements Aircond{
    public String createAircond(a){
        return "Xiaomi Air Conditioner"; }}Copy the code

If we want to use the factory method pattern to write this example is to add mobile phone factory, microwave oven plant, air conditioning plant, if this time we have other companies also to produce mobile phones, microwave ovens, air conditioning, the more we built several instances, this time we abstract factory method pattern is needed.

For example, Gree will also produce mobile phones, microwave ovens and air conditioners at this time. The code is as follows.

// Specific product category
public GeliPhone implements Phone{
    public String createPhone(a){
        return Gree Mobile phone; }}public GeliMicro implements Micro{
    public String createMircro(a){
        return Gree Microwave Oven; }}public GeliAircond implements Aircond{
    public String createAircond(a){
        return "Gree air Conditioning"; }}// Abstract the factory interface
public interface Creator{
    Phone createPhone(a);
    Mircro createMircro(a);
    AirCond createAirCond(a);
}
// Specific factory of Xiaomi
public class XiaomiFactory implements Creator{
    public Phone createPhone(a){
        return new XiaomiPhone();
    }
    public Mircro createMircro(a){
        return new XiaomiMircro();
    }
    public AirCond createAirCond(a){
        return newXiaomiAirCond(); }}// Gree specific factory
public class GeliFactory implements Creator{
    public Phone createPhone(a){
        return new GeliPhone();
    }
    public Mircro createMircro(a){
        return new GeliMircro();
    }
    public AirCond createAirCond(a){
        return newGeliAirCond(); }}/ / test
public class TestFactory{
    public static void main(String []args){
        // Produce xiaomi products
        Creator creator = new XiaomiFactory();
        String phone = creator.createPhone().createPhone();
        String mircro = creator.createMircro().createMircro();
        String airCond= creator.createAirCond().createAirCond();
        // Produce gree products
        creator = newGeliFactory(); phone = creator.createPhone().createPhone(); mircro = creator.createMircro().createMircro(); airCond= creator.createAirCond().createAirCond(); }}Copy the code

Through the above code can see out the abstract factory pattern than the factory method pattern in the case of multiple products, to use more concise (although I did not use the factory method to realize the example above, but you see the officer I the above articles are expected to write their own factory method to realize the above example code!)

I hope you can have some new understanding of these three modes and apply them flexibly so that the purpose of thousand chueh can be achieved.

conclusion

In this issue, Qian Jue introduces three types of factory mode, namely simple factory mode, factory method mode and abstract factory mode. I hope you will have a new understanding of this factory mode after reading this article.

First of all, we moved from simple factory mode to factory method mode because the simple factory mode violates the open and close principle, so the factory method mode came into being. From factory method mode to abstract factory mode, the abstract factory mode compensates for the problem that only one series of products can be created in the factory method mode.

And you can try to do it yourself using the factory method for my last example above.

Finally thank you for watching, if you see the officials think that Qian Jue wrote a good point to pay attention to Qian Jue, also welcome to find me to play wechat oh, wechat search Qian Jue (Jue).

Next: Observer mode.