preface

Today, let’s share the factory mode in design mode

I. Factory model

As we all know, there are 23 design patterns, which can be divided into three broad categories based on function and usage scenarios:

  • Creation pattern
  • Structural mode
  • Behavioral pattern

Factory Pattern, is a very common design Pattern, belongs to the creation Pattern, the main role is to create objects

Schematic diagram

Let’s start with a little chestnut

Ii. Simple Factory Mode (not 23)

Schematic diagram

There are many examples, such as various brands of computers, mobile phones, furniture…

Take the case of laptops

Extract the public Interface

There is only one interface to return to the brand

public interface ILaptop {
    String brand();
}1.23..
Copy the code

Interface implementation class

Here are just two examples

public class HuaWeiLaptop implements ILaptop{
    @Override
    public String brand() {
        return "HuaWei";
    }
}
​
public class MacLaptop implements ILaptop {
    @Override
    public String brand() {
        return "Mac"; }}1.23.4.. 56.7.8.9.10.11.12.13..
Copy the code

The factory class

The main one is the factory class, to which we will give the ability to create objects

public class LaptopFactory {
​
    public static ILaptop createLaptop(String brand){
        switch (brand){
            case "HuaWei":
                return new HuaWeiLaptop();
            case "Mac":
                return new MacLaptop();
            default:
                return null; }}}1.23.4.. 56.7.8.9.10.11.12.13..
Copy the code

test

In this way, we have simply completed the application of a factory pattern ~, after the creation of objects directly call the factory method can be

public class LaptopMain {
    public static void main(String[] args) {
        ILaptop hw = LaptopFactory.createLaptop("HuaWei");
        Stringbrand = hw.brand(); System.out.println(brand); }}1.23.4.. 56.7..
Copy the code

Of course, this is the simplest example of the factory pattern, also known as the Simple Factory pattern

Of course, this has obvious drawbacks, so let’s look at the factory method pattern

3. Factory method mode

Schematic diagram

If you think about simple factory writing, it doesn’t make sense to encapsulate all the operations that create an object in a single factory, so we need to decouple it further

Extract the factory public interface

public interface ILaptopFactory {
    ILaptop createLaptop();
}1.23..
Copy the code

Factory implementation class

public class HuaweiLaptopFactory implements ILaptopFactory{
    @Override
    public ILaptop createLaptop() {
        return newHuaWeiLaptop(); }}1.23.4.. 56..
Copy the code

test

Simply change the first two lines of code in the above test case

 HuaweiLaptopFactory huaweiLaptopFactory = new HuaweiLaptopFactory();
 ILaptop mac =  huaweiLaptopFactory.createLaptop();1.2.
Copy the code

Is it easy to complete the factory mode

Abstract factory model

Schematic diagram

The factory must have more than one production line. It must have other businesses, such as mobile phones and other electrical appliances.

So let’s repeat the notebook product example above, create some other classes, and then create it from the factory class as well.

The abstract factory

Start by defining an abstract factory

public abstract class AbstractFactory {
    public abstract IPhone createPhone();
    public abstract ILaptop createLaptop();
}1.23.4..
Copy the code

Factory implementation class

There is only one more

public class HuaweiFactory extends AbstractFactory{
    @Override
    public IPhone createPhone() {
        return new HuaWeiPhone();
    }
​
    @Override
    public ILaptop createLaptop() {
        return newHuaWeiLaptop(); }}1.23.4.. 56.7.8.9.10.11..
Copy the code

Five, the summary

When using the factory pattern, we can find abstract factories from simple factories (not 23) — factory method

This is an ever-expanding, decoupled process that allows us to choose between projects as needed

For example, if the product is more than abstract factory, single word can directly use the factory or simple factory

So far, we have learned that the factory pattern belongs to the creation pattern in Design Patterns 23. Its main purpose is to create objects and facilitate program decoupling.

Next, let’s think about Spring in relation to the factory pattern

Speaking of which, what do you have in mind?

If you don’t know, just say Factory, Factory, Factory, hahaha ~

You know, those two things just popped into your head

  • BeanFactory
  • FactoryBean

As the name suggests, these two items are related to factories (getting objects via getBean and getObject, respectively).

So let’s introduce them first

Sixth, the BeanFactory

The first sentence of the source code

The root interface for accessing a Spring bean container.

You can see that it is a very core component.

Follow strictThe life cycle

As you can see, creating a Bean through the BeanFactory is a very strict process and tedious.

methods

There are many methods, such as alias, type, singleton, prototype, etc

Get the object via getBean

The main role

Generate the corresponding Bean object based on the BeanDefinition.

Seven, FactoryBean

The source code

You can find just three methods, a small factory

Return an object using the getObject method

When getting an object:

  • ifbeanNamewithout&Number, then get isGeneric type TThe object.
  • If you add&Number, get the implementationFactoryBeanObjects of the interface itself, such asEhCacheFactoryBean

Because of its small size, it is also widely used within Spring and in integrating Spring with third-party frameworks or components.

What is the difference between a BeanFactory and a FactoryBean?

  • BeanFactoryIt is a large factory, the foundation of IOC container, which is cumbersomebeanLifecycle processes can produce a variety ofBean
  • FactoryBeanIt’s a small factory, and it’s one of its ownBean, but can generate otherBean

One last question

Use of factory pattern in Spring

Since it’s all about the factory, let’s pick a soft touch

FactoryBean factory template diagram

You can see that as with the factory method pattern we introduced above, common interfaces and different implementation classes get objects through concrete factories.

BeanFactory is a similar thing. I won’t draw it

Ten,

So let me draw a picture to summarize