preface

As the name suggests, this design Patterns Study Room series takes you through common design patterns. The main contents are:

  • The model ofintroduce, including:
    • Introduction, intention (explanation in plain English)
    • Class diagram, sequence diagram (theoretical specification)
  • Code examples for this pattern: What does code familiar with this pattern look like
  • Advantages and disadvantages of this mode: Mode is not a panacea, and can not be abused
  • A practical use case for this pattern: Learn where it is used in important source code

The series will be updated gradually on my blog and official account (see the blog at the bottom of the post)

I also hope that the audience master can pay attention to my personal public account: back-end technology ramble, will not miss the wonderful and good-looking articles.

Series review

  • Introduction: Why do we use Design Patterns?
  • 【 Design Pattern Study Room 】 Builder pattern
  • 【 Design Pattern Study Room 】 Prototype pattern
  • 【 Design Patterns Study Room 】 Thoroughly understand singleton patterns

Creation – Simple factory/Factory pattern/Abstract factory

primers

Factory mode is a very important creation mode, but factory mode is divided into many kinds, and there are many online articles, many of the definition of factory mode is not very clear, and even conflict with each other, this paper hopes to put together the form of series, and strive to use the most concise language to clarify the factory mode.

Let’s start with a factory schema definition:

“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to Subclasses. “Define an interface for creating objects in the base class and let subclasses decide which class to instantiate. The factory method lets instantiation of a class be deferred to subclasses.

With the factory pattern, we can separate the creation and use of objects. To prevent the data and code used to instantiate a class from being scattered across multiple classes.

The main forms of factory mode are as follows:

  • Simple/Static Factory
  • Factory Method
  • Abstract Factory

intentions

1. Simple/Static Factory

Let’s start with the simple factory pattern, which refers to creating an object without exposing the internal details to the customer and providing a common interface for creating the object.

In the simple factory pattern, you can return instances of different classes depending on the parameters.

2. Factory Method

The factory method can also be called:

  • The factory pattern
  • Virtual Constructor pattern
  • The Polymorphic Factory pattern

The factory pattern uses factory subclasses to determine which specific product classes should be instantiated. Instead of designing a single factory class to be responsible for all product creation, you delegate the creation of specific products to a specialized factory subclass.

This characteristic undoubtedly makes the factory method mode superior to the simple factory mode, and more in line with the “open and close principle”.

3. Abstract Factory

Before we look at abstract factories, what is the product hierarchy and product family

Product family: in the abstract factory pattern, product family is to point to by the same factory, located in different level of product structure in a set of products, such as haier electrical appliances factory production of TV sets, refrigerators, haier haier haier TV in the TV product hierarchy, haier refrigerators in the refrigerator in the hierarchy.

Product hierarchy: hierarchy the inheritance structure of products, such as an abstract class is a TV set, its subclasses are haier, hisense TV, TCL, TVS, abstract and specific brands, constitute a product hierarchy between abstraction is the parent of the television, and specific brand of TV set is its subclasses.

The factory method pattern addresses one product hierarchy, while the abstract factory pattern addresses multiple product hierarchies. One factory hierarchy can be responsible for creating product objects in multiple different product hierarchies.

Abstract factory pattern is the most abstract and general form of all factory patterns.

If you still don’t understand abstract factories, don’t worry. The code examples below will give you a better understanding.

The class diagram

If you don’t understand the UML class diagram, take a quick look at the diagram and Google it to learn more:

1. Simple/Static Factory

The simple Factory pattern contains the following roles:

  • Factory: The Factory role is responsible for implementing the internal logic that creates all instances
  • Product: The abstract Product role is the parent class of all objects created and is responsible for describing the common interface shared by all instances
  • ConcreteProduct: a ConcreteProduct role is a creation target, and all created objects act as instances of a concrete class for this role.

2. Factory Method

(Change the factory to abstract factory and concrete factory instead of simple factory)

  • Factory: Abstract Factory. In this role is the core of the Factory method pattern. Any Factory class that creates objects in the pattern must implement this interface. In real systems, this role is also often implemented using abstract classes.
  • ConcreteFactory: ConcreteFactory: a concrete Java class that implements an abstract factory interface. Concrete factory roles contain business-specific logic and are invoked by consumers to create concrete product objects.
  • Product: Abstract Product, a superclass of objects created by the factory method pattern, that is, a common parent or shared interface for all Product classes. In real systems, this role is also often implemented using abstract classes.
  • ConcreteProduct: a ConcreteProduct. This role implements the interface declared by the abstract Product. Each object created by the factory method pattern is an instance of a ConcreteProduct.

3. Abstract Factory

The abstract factory pattern contains the following roles:

  • AbstractFactory: AbstractFactory
  • ConcreteFactory: ConcreteFactory
  • AbstractProduct: AbstractProduct
  • Concreteproducts: Concrete products

You will find that the role of the factory pattern and the abstract factory are the same.

Sequence diagram

A Sequence Diagram is a Diagram that shows the interaction between objects arranged in chronological order. The sequence diagram shows the interacting objects and the order in which messages are exchanged between them.

We can take a quick look at the sequence diagram, and if you’re interested you can dig a little deeper:

1. Simple/Static Factory

2. Factory Method

3. Abstract Factory

Code sample

In the code presented, each class is distinguished by a role

1. Simple/Static Factory

Code from:

www.jianshu.com/p/d1b6731c1…

Factory — LoginManager
public class LoginManager {
    public static Login factory(String type) {if(type.equals("password")) {return new PasswordLogin();
            
        }else if(type.equals("passcode")) {return new DomainLogin();
            
        }else{/** * throw new RuntimeException("Login type not found"); }}}Copy the code
Abstract product – Login interface
Public Boolean verify(String name, String password); }Copy the code
The product is PasswordLogin
public class PasswordLogin implements Login { @Override public boolean verify(String name, String password) {// TODO auto-generated method stub /** * Service logic */return true; }}Copy the code

Client call

public class Test {
    public static void main(String[] args) {
        String loginType = "password";
        String name = "name";
        String password = "password";
        Login login = LoginManager.factory(loginType);
        boolean bool = login.verify(name, password);
        if(bool) {/** * business logic */}else{/** ** business logic */}}}Copy the code

If the simple factory pattern above is not used, the login Servlet code is verified as follows, and you can see that the code is highly coupled:

public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        String loginType = "password";
        String name = "name";
        String password = "password"; // Handle password authenticationif(loginType.equals("password")){
            PasswordLogin passwordLogin = new PasswordLogin();
            boolean bool = passwordLogin.verify(name, password);
            if(bool) {/** * business logic */}else{/** * business logic */}} // handles domain authenticationelse if(loginType.equals("passcode")){
            DomainLogin domainLogin = new DomainLogin();
            boolean bool = domainLogin.verify(name, password);
            if(bool) {/** * business logic */}else{/** ** business logic */}}else{/** ** business logic */}}}Copy the code

2. Factory Method

Code from: www.jianshu.com/p/1cf9859e0…

(Change the factory to abstract factory and concrete factory instead of simple factory)

Abstract product interface – ILight: a product with both switching functions

public interface ILight
    {
        void TurnOn();
        void TurnOff();
    }
Copy the code

Specific product category — BulbLight

 public class TubeLight implements ILight
    {
        public void TurnOn()
        {
            Console.WriteLine("TubeLight turns on.");
        }

        public void TurnOff()
        {
            Console.WriteLine("TubeLight turns off."); }}Copy the code

Abstract factory class – ICreator

public interface ICreator
    {
        ILight CreateLight();
    }
Copy the code

The specific factory class — BulbCreator

 public class BulbCreator implements ICreator
    {
        public ILight CreateLight()
        {
            returnnew BulbLight(); }}Copy the code

Client call

Static void Main(string[] args) {ICreator creator = new BulbCreator(); ILight light = creator.CreateLight(); light.TurnOn(); light.TurnOff(); Creator = new TubeCreator(); light = creator.CreateLight(); light.TurnOn(); light.TurnOff(); }Copy the code

In this example, each concrete factory class is responsible for producing only one type of product, but each concrete factory class can also maintain a small number of product instance objects internally, similar to the simple factory pattern.

3. Abstract Factory

Code from: www.jianshu.com/p/d6622f3e7…

Abstract product: Apple series

public interface Apple
     {
        void AppleStyle();
    }
Copy the code

Abstract products: Samsung series

public interface Sumsung
     {
        void BangziStyle();
   }
Copy the code

Specific product: iPhone

public class iphone implements Apple
     {
         public void AppleStyle()
         {
            Console.WriteLine("Apple's style: iPhone!"); }}Copy the code

Specific product: iPad

 public class ipad implements Apple
    {
 
         public void AppleStyle()
        {
             Console.WriteLine("Apple's style: iPad!"); }}Copy the code

Product: Note2

public class note2 implements Sumsung
     {
         public void BangziStyle()
         {
            Console.WriteLine("Bangzi's style : Note2!"); }}Copy the code

The abstract factory

public interface Factory
     {
         Apple createAppleProduct();
         Sumsung createSumsungProduct();
     }
Copy the code

Mobile phone factory

public class Factory_Phone implements Factory
     {
         public Apple createAppleProduct()
         {
             return new iphone();
         }
 
         public Sumsung createSumsungProduct()
         {
             returnnew note2(); }}Copy the code

Pad factory

public class Factory_Pad implements  Factory
     {
         public Apple createAppleProduct()
         {
             return new ipad();
         }
 
         public Sumsung createSumsungProduct()
         {
             returnnew Tabs(); }}Copy the code

Client call

public static void Main(string[] args)
         {
              // The buyer wants an iPad and a Tab
              Factory factory = new Factory_Pad();
              Apple apple = factory.createAppleProduct();
              apple.AppleStyle();
              Sumsung sumsung = factory.createSumsungProduct();
              sumsung.BangziStyle();
  
             // The buyer wants another iPhone and a Note2
             factory = new Factory_Phone();
             apple = factory.createAppleProduct();
             apple.AppleStyle();
             sumsung = factory.createSumsungProduct();
             sumsung.BangziStyle();
         }
Copy the code

The following code is the calling code of the factory mode that we have just seen. Do you see any differences? The factory method only cares about which product family, while the abstract factory also considers the hierarchical structure of the product, that is, whether it is made by Apple or Samsung. Even though they’re both cell phones!

Static void Main(string[] args) {ICreator creator = new BulbCreator(); ILight light = creator.CreateLight(); light.TurnOn(); light.TurnOff(); Creator = new TubeCreator(); light = creator.CreateLight(); light.TurnOn(); light.TurnOff(); }Copy the code

To sum it up again with the words in the intention:

The factory method pattern addresses one product hierarchy, while the abstract factory pattern addresses multiple product hierarchies. One factory hierarchy can be responsible for creating product objects in multiple different product hierarchies.

The advantages and disadvantages

1. Simple/Static Factory

advantages
  • Easy to construct and simple logic.
disadvantages
  • If a new product is to be added, a new product class must be added at the same time, and the factory class must be modified to add an else if branch. This violates the “open-close principle” of closing changes.
  • The instance creation logic of all classes is collected in one factory class, which violates the principle of responsibility assignment of high cohesion. All creation logic is centralized in one factory class, and all business logic is implemented in this factory class. When it doesn’t work, the whole system is affected. Therefore, it should be used only in very simple cases, such as when the factory class is responsible for creating a small number of objects.
  • The simple factory pattern uses a static factory approach that prevents the factory roles from forming an inheritance-based hierarchy.

2. Factory Method

advantages
  • In the factory method pattern, the factory method is used to create the product that the customer needs, and it also hides the details of which specific product class will be instantiated from the customer. The user only needs to care about the factory for the desired product, not the creation details, or even the class name of the specific product class.
  • The factory method pattern is also called polymorphic factory pattern because all concrete factory classes have the same abstract parent class.
  • Another advantage of using the factory method pattern is that when you add a new product to the system, you don’t need to modify the abstract factory and the interface provided by the abstract product, you don’t need to modify the client, or you don’t need to modify other concrete factories and concrete products, you just need to add a concrete factory and concrete products. As a result, the system is very scalable, fully adhering to the “open closed principle”, which is better than the simple factory model.
disadvantages
  • When adding new products, it is necessary to write new concrete product classes and provide corresponding concrete factory classes. The number of classes in the system will increase in pairs, which increases the complexity of the system to a certain extent. More classes need to be compiled and run, which will bring some extra overhead to the system.
  • Considering the scalability of the system, it is necessary to introduce an abstraction layer, which is defined in the client code, increasing the abstractness and difficulty of understanding of the system, and DOM, reflection and other technologies may be used in the implementation, increasing the difficulty of the implementation of the system.

3. Abstract Factory

advantages
  • Abstract factory pattern can achieve high cohesion and low coupling design, so abstract factory pattern has been widely used.
  • Adding new concrete factories and product families is convenient because a concrete factory implementation represents a product family and does not need to modify existing systems to conform to the “open closed principle.”
disadvantages

Inclination of the open close principle (easy to add new factories and product families, troublesome to add new product grade structure)

Application Scenario Example

1. Simple/Static Factory

The factory class is responsible for creating fewer objects: Because there are fewer objects created, the business logic in the factory method is not too complicated.

Used in Java JDK
  1. Simple factory patterns are widely used in JDK libraries, such as the utility class java.text.dateFormat, which is used to format a local date or time.
public final static DateFormat getDateInstance();
public final static DateFormat getDateInstance(int style);
public final static DateFormat getDateInstance(int style,Locale
locale);
Copy the code
  1. Java encryption technology get key generators for different encryption algorithms:
KeyGenerator keyGen=KeyGenerator.getInstance("DESede");
Copy the code
  1. Create password:
Cipher cp = Cipher.getInstance("DESede");
Copy the code

2. Factory Method

Used in Java JDK
  • Factory methods in JDBC:
Connection conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=DB; user=sa; password=");
Statement statement=conn.createStatement();
ResultSet rs=statement.executeQuery("select * from UserInfo");
Copy the code
  • java.util.Calendar
  • java.util.ResourceBundle
  • java.text.NumberFormat
  • java.nio.charset.Charset
  • java.net.URLStreamHandlerFactory
  • java.util.EnumSet
  • javax.xml.bind.JAXBContext

3. Abstract Factory

The abstract factory pattern can be used when:

  • It is important for all types of factory patterns that a system should not depend on the details of how product class instances are created, combined, and expressed.
  • There is more than one product family in the system and only one of them is used at a time. (Difference from factory method pattern)
  • Products belonging to the same product family will be used together, and this constraint must be reflected in the design of the system.
  • The system provides a library of product classes, all of which appear in the same interface, so that the client is implementation-independent.
Used in Java JDK
  • javax.xml.parsers.DocumentBuilderFactory
  • javax.xml.transform.TransformerFactory
  • javax.xml.xpath.XPathFactory

conclusion

Abstract factory pattern can define and implement more than one interface, and a factory can generate more than one product class. Abstract factory pattern implements the “open-closed” principle better, and is the more abstract and general pattern among the three patterns.

At the end of the day, however, the factory model still adds some complexity to the code. Is there a way to solve the extensibility problem of the code in the future without having to create a factory?

The answer is yes. Through inversion of control (IOC), when an object is created, it is passed a reference to the object on which it depends by an external entity that regulates all objects in the system. In other words, dependencies are injected into objects. (DI) is the core idea of Spring. You can check out the Spring ideas article for yourself.

In other words, I really want to summarize the knowledge related to Spring source code recently, and I am studying it.

reference

  • HEAD FIRST Design Patterns
  • www.jianshu.com/p/d1b6731c1…
  • www.jianshu.com/p/1cf9859e0…
  • www.jianshu.com/p/d6622f3e7…
  • The design – patterns. Readthedocs. IO/zh_CN/lates…

Pay attention to my

I’m a back-end development engineer.

Focus on back-end development, data security, crawler, Internet of Things, edge computing and other directions, welcome to exchange.

I can be found on every platform

  • Wechat official account: A ramble on back-end technology
  • Making: @ qqxx6661
  • CSDN: @ Rude3Knife
  • Zhihu: @ Zhendong
  • Jane: @pretty three knives a knife
  • Nuggets: @ pretty three knife knife

Original blog main content

  • Java interview knowledge review manual
  • Design Patterns/Data Structures study room
  • Leetcode/ Sword finger offer algorithm parsing
  • SpringBoot/SpringCloud rookie combat series
  • Crawler related technical articles
  • Technical articles related to back-end development
  • Anecdotes/good books to share/personal interests

Personal public account: Back-end technology ramble

If the article is helpful to you, you might as well collect, coin, forward, in the look ~