Three implementations factory pattern, it's that simple!

Factory Pattern

Factory pattern is commonly used in the development of a design pattern to solve the problem of great programming every aspect of a design pattern will, factory pattern is the same, it will use simple language to explain what a factory pattern? Kind of factory model, code examples, and the advantages and disadvantages of each scene mode is suitable plant factory mode.

Why, if using the factory pattern?

First, we use a vivid story to describe what is under the factory pattern, it makes you faster understanding of the factory model, to lay the foundation for the subsequent understanding of several factory pattern implementation.

If you need to allow the company to open a proof of income to provide proof of income for their home loans, the process generally open proof of income are:

  1. Print proof of income;
  2. The company's cover chapter on proof of income;

Throughout the process, you can know that you need to create a proof of income, proof of income and use the information to provide home loans. This process, there are two key behaviors: Create proof of income, proof of income use. Proof of income in the process of creating is divided into two steps: print, stamp. Colleagues are not familiar with this process when creating proof of income, often resulting in a lot of trouble to open proof of income frequently blocked, so the company decided to open proof of income it employees to be optimized, used to take two steps to do now only need to send a message to the financial sector, the financial sector will be able to keep the cover of Chapter proof of income to the station before the commute, which is encountered in life 工厂模式.

Having said that, 工厂模式exactly which problems in life do?

In this case life, it allows employees to create a proof of income this matter easier, employees need to know is how to create a proof of income, only need to send a message to the financial sector, the financial sector will help employees cover printing and chapter. And in the subsequent development of the company, if you need more cover in Chapter proof of income, the employee does not need to be familiar with the entire process to take its own, holding proof of income Boduantui to the various departments to seal.

Then, in the world of the program, code demonstrates how to use the staff as a loan to buy a house, proof of income to the company to open this behavior? How is the code to show the factory model of it?

Analogy above example, if there is a 收入证明类create only need to click on the new line, the parameters are 打印证明and 给证明盖章, if follow-stamped proof of income has changed, you need to modify the parameters. This requires a lot of change call creates 收入证明类new code.

At this pattern can then use the factory, the factory mode will use to create and separate classes of classes, Class A wants to call when the Class B, then A except the call to B, B is instantiated as for, on to plant class.

Some people say that, you can put these constructor code creation process into the class, the same repetition rate can be reduced, and also the role of the constructor to initialize the object itself. For this view, we can compare the factory mode compared to the advantages of the constructor:

advantage:

  1. Static factory methods and constructors did not have a name, because the plant can have multiple methods to distinguish the various methods by name, but only one constructor name, can only be distinguished by the parameters, using a static factory method is more straightforward.

  2. Static factory method to support conditional instantiation, that when you create an object, sometimes need to add some conditions should be created to determine whether, if the condition returns one instance, does not satisfy the returns NULL, such as the Singleton pattern. We can not do so when the constructor, the constructor function of the need to maintain a single, only for the construction and presence, while static factory method can be very simple to do.

  3. The method can return return type subtype

This is the factory pattern to create some advantages in on the object, and the factory model is the core of knowledge: the creation and use of objects do separation. Please meditation three times.

Seize the core point, go to the factory to understand the various patterns to achieve more than just a simple factory pattern can generally be divided into three types:

  • Simple / static factory pattern
  • Factory Method pattern
  • Abstract factory pattern

We learn the steps in: the factory method pattern to a simple static factory pattern to abstract factory pattern, very simple example, one can understand, the text of the code I put the students interested on github can download:

github Address: java23 code sample design patterns - the factory mode

I know we are all caring people, white whore of course not your habit, welcome to a wave of triple qualities: attention, thumbs up, point star

Factory Method pattern

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

If we need to build a mobile phone in the factory, then the abstract class to define a phone, the phone must have a function call, add a call abstract methods

package com.shuai.design.factory.normals;

public abstract class Phone {

    // 所有的手机必须要有打电话的功能
    public abstract void call();

}

Creating a mobile phone factory interface, which has a createPhone method, other types of mobile phones should inherit this interface must implement this method to create a mobile phone

package com.shuai.design.factory.normals;

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

public interface PhoneFactory {

    Phone createPhone();
}

Creating millet phone category. Inheritance phone, call the method to achieve

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");
    }
}

Creating millet mobile phone factory

package com.shuai.design.factory.normals;

public class MiPhoneFactory implements PhoneFactory {

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

Similarly millet phone, Huawei cell phone to achieve classes, inheritance phoen abstract class that implements the method call

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 cell phone to achieve factory

package com.shuai.design.factory.normals;

public class HuaWeiPhoneFactory implements PhoneFactory{

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

Simple static factory pattern

Static factory method pattern relative to the plant much simpler, first create an abstract class phone

package com.shuai.design.factory.simples;

public abstract class Phone {

    // 所有的手机必须要有打电话的功能
    public abstract void call();

}

Construction of the factory and then create a class of phone, creating different types of mobile phones based on the type of incoming

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();
        }
    }
}

Realization of millet phone class

package com.shuai.design.factory.simples;

public class MiPhone extends Phone {

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

Huawei cell phone to achieve class

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: providing an interface for the creation of a group of related or interdependent objects, but without specifying their concrete classes

Pictured:

Abstract Factory

Here is a way to create a mobile phone to achieve the abstract factory, create a phone abstract class, which not only call methods, as well as the type of phone screen

package com.shuai.design.factory.abstracts;

public abstract class Phone {

    // 所有的手机必须要有打电话的功能
    public abstract void call();

    // 手机的屏幕类型
    public abstract void screenType();

}

Then create a phone interface to build the parent plant

package com.shuai.design.factory.abstracts;

public interface PhoneFactory {

    Phone createMiPhone();

    Phone createHuaWeiPhone();

}

First of all mobile phones and millet Huawei phones must implement call features, rewrite method call

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");
    }

}

In the divided millet folding screen phone based on the phone's screen type:

package com.shuai.design.factory.abstracts;

public class FoldingScreenMiPhone extends MiPhone {

    @Override
    public void screenType() {
        System.out.println("this is 小米折叠屏手机");
    }

}

In the divided Huawei folding screen phone based on the phone's screen type:

package com.shuai.design.factory.abstracts;

public class FoldingScreenHuaWeiPhone extends HuaWeiPhone {

    @Override
    public void screenType() {
        System.out.println("this is 华为折叠屏手机");
    }

}

In the divided screen phone millet curved screen based on the phone's screen type:

package com.shuai.design.factory.abstracts;

public class CurvedScreenMiPhone extends MiPhone {

    @Override
    public void screenType() {
        System.out.println("this is 小米曲面屏手机");
    }
}

In the curved screen is divided into Huawei's mobile phone according to the phone's screen type:

package com.shuai.design.factory.abstracts;

public class CurvedScreenHuaWeiPhone extends HuaWeiPhone{

    @Override
    public void screenType(){
        System.out.println("this is 华为曲面屏手机");

    }

}

For different types of mobile phone screens, abstract type screen constructed according to the plant, plant cell phone screen and the curved surface screen folding mobile phone factory:

package com.shuai.design.factory.abstracts;
//曲面屏手机工厂
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;
//折叠屏手机工厂
public class FoldingScreenPhoneFactory implements PhoneFactory{

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

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

}

Write a test class test results:

package com.shuai.design.factory.abstracts;

public class Test {

    public static void main(String[] args) {

        // 创建一个华为曲面屏手机
        CurvedScreenHuaWeiPhone curvedScreenHuaWeiPhone = new CurvedScreenPhoneFactory().createHuaWeiPhone();
        System.out.println("curvedScreenHuaWeiPhone 的手机类型为:");
        curvedScreenHuaWeiPhone.screenType();

        // 创建一个小米曲面屏手机
        CurvedScreenMiPhone curvedScreenMiPhone = new CurvedScreenPhoneFactory().createMiPhone();
        System.out.println("curvedScreenMiPhone 的手机类型为:");
        curvedScreenMiPhone.screenType();

        // 创建一个华为折叠屏手机
        FoldingScreenHuaWeiPhone foldingScreenHuaWeiPhone = new FoldingScreenPhoneFactory().createHuaWeiPhone();
        System.out.println("foldingScreenHuaWeiPhone 的手机类型为:");
        foldingScreenHuaWeiPhone.screenType();

        // 创建一个小米折叠屏手机
        FoldingScreenMiPhone foldingScreenMiPhone = new FoldingScreenPhoneFactory().createMiPhone();
        System.out.println("foldingScreenMiPhone 的手机类型为:");
        foldingScreenMiPhone.screenType();

    }

}

Abstract factory pattern usage scenarios: a family of objects (or a set of objects without any relationship) have the same constraints, can abstract factory. By factory class, as long as you know who the factory class that I can create an object of a need

1

Disadvantages :

Extended product family difficulties. Such as adding a phone with a stylus type in the type of phone, then each class has been achieved on both phones need to implement this method. This is a serious violation of the principle of opening and closing.

advantage:

Increased level of simplicity. If the addition of a bi-fold and tri-fold screen screen mobile phone in a folded screen phone which is relatively simple, only the following modifications need to build factories on the line in the folding screen phone.

to sum up

Will be used the next fact, the general development process, we use a more simple factory pattern, abstract factory pattern, then business needs relatively large. If you have a better point of view, are welcome in the comments area proposed, learn from each other.

References:

I welcome attention

Published 16 original articles · won praise 16 · views 2593

Guess you like

Origin blog.csdn.net/weixin_43973190/article/details/105066571