[Design Mode] to create a model of the factory model type

github repository Address: github.com/qiudao12345...

0 Preface

Factory pattern (Factory Pattern) Java is one of the most commonly used design patterns. This type of design pattern belongs create schema, which provides the best way to create objects. In Factory mode, we will not expose the client to create a logical when you create an object, and through the use of a common interface to point to the newly created object

Belong to the factory model to create a schema , it also belongs to the singleton create schema article mentioned me [Design Mode] - is probably the most detailed description of Singleton What difference does it make?

The answer: focus singleton that object in memory of uniqueness , but the focus is the factory model that hides the complexity of the object and details of the creation process , the process of building object transparency, simplification.

ps: the core idea of ​​the factory model that calls for end to hide the details of the build process and, so long as the core module or code for this idea can be said to be using the factory pattern. Factory pattern can have different implementations, while the following three plants mentioned only in different scenarios, the factory model of a simple distinction between it

1. Simple Factory

GOF in talking to the 23 design patterns are not actually contain a simple factory pattern, but the pattern is often encounter

1.1 introduction scene

1.11 Xiao Ming to buy mobile phones

Bob wants to buy two phones, a millet phone, a Huawei phone. Under normal circumstances, if Xiao Ming to buy these two phones, he may need to do is

  • 1. Open the phone, enter the mall millet, millet to enter the mall, find the corresponding models of mobile phones, orders
  • 2. changing clothes to go out, ride, Huawei cell phone into the store, pick the corresponding models of mobile phones, buying the question is, this much trouble, and if he wanted to buy one if the OPPO phone? Would not you have to go to the mall OPPO orders?

It can not engage in a public platform, to buy all brands of mobile phones, just say what you want to what phone model, then the platform will automatically send you the phone?

This is the thinking pattern of the factory!

Unified interface provided by the factory model, we can easily get to the desired object, without the need to focus on their specific details

The following look at UML class diagram simple factory pattern

1.2 UML FIG.

Here there are three main roles

  • 1. Abstract product (Phone) : an abstract factory output of the product, in order to facilitate functional extension
  • 2. Specific Products (XiaomiPhone) : abstract concrete realization of products
  • 3. Plant (SimpleFactory) : Construction of the passed parameters and returns a specific product

In this mode, the call ends only need to hold the factory object, passing in the corresponding product information, you can not care about their specific case creation process and create the details, it is very easy to get to the desired object.

Let's look at the code to achieve

1.3 code implementation

(Example no added very complicated service logic, to simply show this mode)

1.31 abstract product

/**
 * 手机
 * @author qiudao
 */
public interface Phone {
    // 打印品牌
    void printBrand();
}
复制代码

1.32 Specific products

Huawei cell phone

/**
 * 华为手机
 * @author qiudao
 */
public class HuaweiPhone implements Phone{
    @Override
    public void printBrand() {
        //todo  复杂逻辑
        System.out.println("华为牌手机!");
    }
}

复制代码

Millet phone

/**
 * 小米手机
 * @author qiudao
 */
public class XiaomiPhone implements Phone{
    @Override
    public void printBrand() {
        //todo  复杂逻辑
        System.out.println("小米牌手机!");
    }
}
复制代码

1.33 Factory

/**
 * 简单工厂
 *
 * @author qiudao
 */
public class SimpleFactory  {
    // 小米的名
    public final static String XIAOMI_NAME = "xiaomi";
    //华为的名字
    public final static String HUAWEI_NAME = "huawei";
    /**获得手机**/
    public  Phone getPhone(String name) {
        Phone phone;
        // 静态编码校验
        if (XIAOMI_NAME.equals(name)) {
            //todo  复杂逻辑
            phone = new XiaomiPhone();
        } else if (HUAWEI_NAME.equals(name)) {
            //todo  复杂逻辑
            phone = new HuaweiPhone();
        } else {
            throw new NullPointerException("无对应手机");
        }
        return phone;
    }
}
复制代码

1.34 Test

/**
 * 测试简单工厂
 * @author qiudao
 */
public class TestSimpleFactory {
    public static void main(String[] args) {
        // 创建工厂
        SimpleFactory factory = new SimpleFactory();
        Phone huaweiPhone = factory.getPhone(SimpleFactory.HUAWEI_NAME);
        huaweiPhone.printBrand();
        Phone xiaomiPhone = factory.getPhone(SimpleFactory.XIAOMI_NAME);
        xiaomiPhone.printBrand();
    }
}
复制代码

2. factory method

Above us a simple factory pattern, although in this way allows us to easily be able to get to the desired object, but there is a very serious problem, that is, poor scalability, if you want to add a VIVO phone, then we need

  • New VIVO phone category VivoPhone
  • Modify SimpleFactory.getPhone () method so contrary to the opening and closing principle , and on the one hand, people are very fallible animals on the overall logic flow is modified extension, then it is easy to cause problems. On the other hand, all logically coupled in a single class, the coupling of the code will be very high, the system design does not meet the high cohesion and low coupling principle bonded

So this time, we need to reposition itself in the factory method pattern

In order to instantiate operation of the product delay to the sub-class factory is completed, the factory subclasses to decide which one is product specific object should be instantiated. Plant parent class (interface) is responsible for the definition of the product object's public interface, sub-class factory is responsible for creating specific products object.

2.1 introduction scene

In the last scene, a common platform for all mobile phone handset makers have bought it, so if someone want to buy the phone, he can immediately give the phone to him. But the question is, as more and more mobile phone brands, the boss of this discovery platform, the platform is not enough money to buy their mobile phone! This is how to do it?

This time, someone proposes a new model.

  • Engage in a marketing center, all mobile phone manufacturers have settled in the center, if necessary Xiao Ming, then directly into the marketing centers, find the corresponding brand of stagnation. Then buy a mobile phone with them on it, if a new mobile phone manufacturers appears, then just let them set up a marketing center in the stagnation point on the line, so that the platform would not have to buy every brand of mobile phones all over the

This is the core idea of ​​the factory method, we take a look uml map

2.2 UML described with FIG.

There are four roles:

  • 1. abstract product (Phone) : with simple factory
  • 2. Specific Products (HuaweiPhone) : with simple factory
  • 3. Abstract Factory (Factory's) : under a duty to create abstract product interfaces
  • 4. Specific plant (HuaweiPhoneFactory) : create specific products factory, which is determined by the caller using factory

If there is need to add specific product, you only need to

  • 1. Create a product-specific implementation of the abstract product interfaces
  • 2. Create specific product factories, and implement the abstract factory interface
  • 3. Call the end decide which factories to call

2.3 code implementation

2.31 abstract product

/**
 * 手机
 * @author qiudao
 */
public interface Phone {
    // 打印品牌
    void printBrand();
}
复制代码

2.32 Specific products

Huawei cell phone

/**
 * 华为手机
 * @author qiudao
 */
public class HuaweiPhone implements Phone{
    @Override
    public void printBrand() {
        System.out.println("华为牌手机!");
    }
}

复制代码

Millet phone

/**
 * 小米手机
 * @author qiudao
 */
public class XiaomiPhone implements Phone{
    @Override
    public void printBrand() {
        System.out.println("小米牌手机!");
    }
}
复制代码

2.33 Abstract Factory

/**
 * 工厂接口
 * @author qiudao
 */
public interface Factory {
    // 拿到手机
    Phone getPhone();
}
复制代码

2.34 concrete factory

Huawei cell phone

/**
 * 工厂方法的具体工厂
 * @author qiudao
 */
public class HuaweiPhoneFactory implements Factory{
    @Override
    public Phone getPhone() {
        //todo  复杂逻辑
        return new HuaweiPhone();
    }
}
复制代码

Millet phone

/**
 * 工厂方法的具体工厂
 * @author qiudao
 */
public class XiaomiPhoneFactory implements Factory{
    @Override
    public Phone getPhone() {
        //todo  复杂逻辑
        return new XiaomiPhone();
    }
}
复制代码

2.35 Test

/**.
 * 测试工厂方法
 * @author qiudao
 */
public class TestFactoryMethod {
    public static void main(String[] args) {
        System.out.println("工厂方法测试.......");
        Factory xiaomiPhoneFactory  = new XiaomiPhoneFactory();
        Phone xiaomiPhoe = xiaomiPhoneFactory.getPhone();
        xiaomiPhoe.printBrand();
        HuaweiPhoneFactory huaweiPhoneFactory = new HuaweiPhoneFactory();
        Phone huaweiPhone = huaweiPhoneFactory.getPhone();
        huaweiPhone.printBrand();
    }
}
复制代码

3. Abstract Factory

Above we we introduced the factory method pattern, a simple comparison of the factory, factory method obey the opening and closing of principle , in the case of the expansion of the plant will not cause any damage to the original code.

3.1 introduction scene

Funding platform now solved, but it created a new problem: After customers buy a new phone, you also need to buy a mobile phone sets corresponding depending on the model. This is how to do ah? Marketing Center of stagnation which sell mobile phone ah, if customers buy a mobile phone sets, then it would mean that the problem will occur prior to the introduction of factory pattern?

So the person in charge of a new rule: each settled stagnation must provide the corresponding sales service of mobile phone sets

This a good solution to the problem just emerging

3.2 UML described with FIG.

  Abstract factory pattern provides an interface for creating families of related or dependent objects without the need to explicitly specify a specific class. It can be understood as a combination of a plurality of process plants.

Factory method is to create the same level of products, and provides an abstract factory is to create a product family features

  • What is the same level? What is the product family do?

Substituting the words of this scene, millet phone with Huawei mobile phone is the same grade of product, millet mobile phone sets with Huawei mobile phone sets of mobile phone sets are, they are also the same level of product.

The mobile phone with millet millet phone sets is something of the same product family, Huawei cell phone with Huawei mobile phone sets, though not the same thing, but they are Huawei brand, they belong to the same product family.

May be represented by the following FIG.

Once you understand the product level with the product family, we look at the abstract factory uml diagram

His role with the kind of factory method is the same, the only one difference is that the abstract factory plant does not produce a single product, but the production of a product family thing

3.3 code implementation

3.31 abstract product

/**
 * 手机
 * @author qiudao
 */
public interface Phone {
    // 打印品牌
    void printBrand();
}
/**
 * 手机套
 * @author qiudao
 */
public interface PhoneCases {
    // 打印手机套名字
    void printCasesName();
}
复制代码

3.32 Specific products

/**
 * 华为手机
 * @author qiudao
 */
public class HuaweiPhone implements Phone{
    @Override
    public void printBrand() {
        System.out.println("华为牌手机!");
    }
}
/**
 * 小米手机
 * @author qiudao
 */
public class XiaomiPhone implements Phone{
    @Override
    public void printBrand() {
        System.out.println("小米牌手机!");
    }
}
/**
 * 华为手机壳
 * @author qiudao
 */
public class HuaweiPhoneCases implements PhoneCases{
    @Override
    public void printCasesName() {
        System.out.println("华为手机套");
    }
}
/**
 * 小米手机壳
 *
 * @author qiudao
 */
public class XiaomiPhoneCases implements PhoneCases {
    @Override
    public void printCasesName() {
        System.out.println("小米手机套");
    }
}
复制代码

3.33 Abstract Factory

/**
 * 抽象工厂
 *
 * @author qiudao
 */
public interface AbstractFactory {
    // 获取手机
    Phone getPhone();

    // 获取手机套
    PhoneCases getPhoneCases();
}
复制代码

3.34 concrete factory

/**
 * 华为工厂
 * @author qiudao
 */
public class HuaweiFactory implements AbstractFactory {
    @Override
    public Phone getPhone() {
        //todo  复杂逻辑
        return new HuaweiPhone();
    }

    @Override
    public PhoneCases getPhoneCases() {
        //todo  复杂逻辑
        return new HuaweiPhoneCases();
    }
}
/**
 * 小米工厂
 * @author qiudao
 */
public class XiaomiFactory implements  AbstractFactory {
    @Override
    public Phone getPhone() {
        //todo  复杂逻辑
        return new XiaomiPhone();
    }

    @Override
    public PhoneCases getPhoneCases() {
        //todo  复杂逻辑
        return new XiaomiPhoneCases();
    }
}

复制代码

3.35 Test

/**
 * 测试抽象工厂
 * @author qiudao
 */
public class TestAbstractFacoty {
    public static void main(String[] args) {
        System.out.println("抽象工厂测试");
        AbstractFactory xiaomiFactory = new XiaomiFactory();
        Phone xiaomiPhone = xiaomiFactory.getPhone();
        PhoneCases xiaomiPhoneCases = xiaomiFactory.getPhoneCases();
        xiaomiPhone.printBrand();
        xiaomiPhoneCases.printCasesName();
        AbstractFactory huaweiiFactory = new HuaweiFactory();
        Phone huaweiPhone = huaweiiFactory.getPhone();
        PhoneCases huaweiPhoneCases = huaweiiFactory.getPhoneCases();
        huaweiPhone.printBrand();
        huaweiPhoneCases.printCasesName();
    }
}
复制代码

4. factory pattern summary

Incidentally, the above three modes in the factory, and a UML diagram code implementation is not static, but that above examples are representative of the more classic comparison. Many times we will go according to business needs custom extensions or slightly change its structure so that we can achieve functional requirements.

For example, the above abstract factory model, abstract factory can be defined as an abstract class, and then define a method of assembling the phone in an abstract class assemblePhoe ()

 public void  assemblePhone(){
        System.out.println("开始组装");
        this.getPhone().printBrand();
        this.getPhoneCases().printCasesName();
        System.out.println("组装完成");
    }
复制代码

This can be achieved a number of extensions!

Summarize the pros and cons of three kinds of factory pattern

Simple Factory

advantage

Factory class is the key to the whole pattern. Contains the necessary logic judgment, according to outside information given to determine whether an object which specific classes should be created by using the factory class, the outside world can emerge from directly create specific products subject embarrassment just need to be responsible "consumption" objects on it. And do you need these objects exactly how to create and how to organize. Clear the respective responsibilities and rights, help to optimize the entire software architecture.

Shortcoming

Since the factory class centralizes all create logical instances of violation of the principle of high poly allocation of responsibilities within the centralized logic all create a factory to class; it can only be created in advance taking into account the class, if you need to add a new class, we need to change the factory class. When the system is in specific product categories growing time, there may be requirements created by the factory needs of different instances according to different criteria. This judgment and the judgment of the conditions of the specific type of product intertwined, it is difficult to avoid the spread of module functionality, maintenance and expansion of the system is very negative

Factory Method

advantage

Simple plant contrast, the maximum advantage is the factory methods do not require an extension of the original structure changes in line with the principle of opening and closing, reducing the coupling system.

Shortcoming

Every new product will need to add a class, the long run is likely to cause flooding class, increasing the complexity of the system

Abstract Factory

advantage

Increase product family concept, a factory can produce a variety of products, can reduce the number of factory class to some extent, to avoid the proliferation of class. Product between some of the same product family linked operation may be performed (e.g., a mobile phone is assembled above-mentioned example), to reduce the coding amount.

Shortcoming

The basic drawback of the method is the same as with the factory, while the abstract factory, another disadvantage is not flexible enough, for example, the marketing center of Huawei booth just want to sell mobile phones not want to sell mobile phone sets, then use the abstract factory will not only generate unnecessary code that will allow the plant neither fish nor fowl

5. Source Applications

JDK or have a lot of good open source frameworks used in the factory method. The following list a little bit, not in-depth interpretation

Thread pool framework Executors

Executors provides a range of methods to quickly create a thread pool, although it is among the three kinds uml uml structure diagram is not mentioned in the above, but without a doubt it is the use of the factory model, because it hides created for the caller complex process and the details thread pool. Only exposes a simple interface.

Spring Bean container

I believe that many students in the beginner when the spring, will have seen this piece of code

BeanFactory beanFactory = new ClassPathXmlApplicationContext("xxx");
Object obj = beanFactory.getBean("car");
复制代码

Can be seen, this code is also used in the factory model, in fact, the core is spring bean container, the entire container is a plant, at the start of the object instance stored at the factory, then getBean (String beanName) or getBean (Class clazz) to obtain an instance of the plant, rather than by new XXX () way to get the object instance

iterator method in Collection

java.util.Collection interface is defined () method is a factory method abstract iterator.

For iterator () method for Collection abstract factory is a root, the following interfaces as well as the abstract factory List, then there ArrayList other specific plant down.

java.util.Iterator abstract interface is the root of the product, like below ListIterator abstract products, as well as other specific ArrayListIterator products.

The method of using different iterator class concrete factory can be obtained Examples of different specific products.

Mybatis in SqlSessionFactory

SqlSessionFactory for establishing SqlSession from the specified database, the default implementation class is DefaultSqlSessionFactory, if necessary, developers can also implement their own SqlSessionFactory, and this is reflected in the classic factory method

All in all, the factory pattern is very common, it is not difficult to understand, but substituted into the source frameworks in time, it is still reading would be more difficult.

Articles If there are errors, we hope the wing, comments that!

github repository Address: github.com/qiudao12345...

Guess you like

Origin blog.csdn.net/weixin_33912453/article/details/91398615