Moment For Technology

A quick three-minute overview of factory patterns in Spring

Posted on Dec. 3, 2022, 9:09 a.m. by Rita Dunn
Category: The back-end Tag: The back-end spring

This is the first day of my participation in the August More text Challenge. For details, see: August More Text Challenge


Today 4ye will share the factory mode in design mode with friends ?

By the way, I have brought the following three questions, please check out ?

I. Factory model

As we all know, there are 23 design patterns, which can be divided into three categories according to their functions and usage scenarios:

  • Creation pattern
  • Structural mode
  • Behavioral pattern

The Factory Pattern is a common design Pattern. It belongs to the creation Pattern. The main purpose of the design Pattern is to create objects

Schematic diagram

Let's take a small example, ?

Simple Factory mode (not 23)

Schematic diagram

Examples, feel also quite a lot of such as a variety of brands of computers, mobile phones, furniture ah...

Take the laptop

Extract the public interface

There is only one interface for returning brands

public interface ILaptop {
    String brand();
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"; }}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; }}}Copy the code


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

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

Of course, this is the simplest example of a factory pattern, also known as a simple factory pattern

Of course, this also has obvious drawbacks, so let's take a look at the factory method model

Factory method pattern

Schematic diagram

If you think about simple factory writing, it doesn't make sense to encapsulate all of the operations that create objects in a single factory, so let's further decouple

Extract the factory public interface

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

Factory implementation class

public class HuaweiLaptopFactory implements ILaptopFactory{ @Override public ILaptop createLaptop() { return new HuaWeiLaptop(); }}Copy the code


Simply change the first two sentences of the above test case

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

Is it very simple to complete the factory mode ?

Abstract Factory pattern

Schematic diagram

So the factory, it must have more than one production line, it must have other business, such as mobile phones, other appliances and so on.

So let's repeat the laptop example above, create some other classes, and 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();
Copy the code

Factory implementation class

That's just one more

public class HuaweiFactory extends AbstractFactory{ @Override public IPhone createPhone() { return new HuaWeiPhone(); } @Override public ILaptop createLaptop() { return new HuaWeiLaptop(); }}Copy the code


When using the factory pattern, we can see that the factory is abstracted from a simple factory (not 23) -- the factory method -- the factory

This is an extended, decoupled process, and we can choose between items as needed

For example, if there are many products, choose an abstract factory. If there is only one, use a factory or a simple factory directly ?


So far, we know that the factory pattern belongs to the creation pattern in the 23 design patterns. Its main purpose is to create objects and facilitate program decoupling.

Next, let's think about ? in Relation to the factory pattern in Spring

Speaking of which, what comes to mind? ?

If you don't know, say Factory, Factory, Factory... Ha, ha, ha

? BeanFactory, FactoryBean

As the name suggests, these are factory related (getBean and getObject, respectively).

So let's introduce them first, ?


The first sentence of the source code ?

The root interface for accessing a Spring bean container. (IOC root interface)

You can see that it's a very core component.

Follow strictThe life cycle?

As you can see, creating a Bean through the BeanFactory is a very rigorous process, which can be quite tedious.


There are many methods, such as getting aliases, types, singletons, prototypes and so on

Get the object through getBean

The main role

Generate the corresponding Bean object from the BeanDefinition.


The source code

Can find so three methods, a small factory ~

Return an object via the getObject method

When obtaining an object:

  • ifbeanNamewithoutIs obtainedGeneric type TThe object.
  • If you addNumber, get is implementedFactoryBeanAn object of the interface itself, such asEhCacheFactoryBean

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

What is the difference between A BeanFactory and a FactoryBean?

  • BeanFactoryIs a large factory, is the foundation of IOC container, there are cumbersomebeanThe lifecycle processing process can produce a variety ofBean
  • FactoryBeanIt's a small factory, and it's a factory itselfBean, but can generate othersBean

One last question ~?

Use of factory mode in Spring

Since it is related to the factory, then we pick a soft persimmon to pinch ?

FactoryBean factory pattern diagram

You can see that as with the factory method pattern we introduced above, the public interface and the different implementation classes get the object through the concrete factory.

The BeanFactory is similar, so I won't draw it


Let me draw a picture to sum it up ?

The last

Welcome to explore the problem together

If you think this article is good, please support it with more likes ?

Let's start this unexpected meeting! ~

Please leave a message! Thanks for your support! ヾ(≧▽≦*)o

I'm 4ye. Next time we should... See you soon!! ?

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.