The creative design pattern is responsible for object creation and management as the name implies. The singleton pattern and the prototype pattern are easier to understand. The singleton pattern has only one instance of an object in memory. The prototype pattern requires that a new object be created by copying. The concepts of the factory method pattern, the abstract factory pattern, and the builder pattern are confusing.

1 Factory Mode

Factory patterns are divided into simple factory patterns, factory method patterns and abstract factory patterns. However, in GOF’s Design Patterns, the simple factory is considered a special case of the factory method pattern.

1.1. Simple factory

A simple factory, also known as a static factory, is usually an inherited class or interface implementation of a specific product.

/** * Products */
public interface Car {

    public void run();
}
Copy the code
/** * Specific product factory */
public class AodiCar implements Car{
    @Override
    public void run() {
        System.out.println("i am aodi car"); }}Copy the code
/** * Specific product factory */
public class BaomaCar implements Car {
    @Override
    public void run() {
        System.out.println("i am baoma car"); }}Copy the code
/** * Core factory class */
public class CarFactory {

    public static Car createCar(String name) {
        if (name.equals("aodi")) {
            return new AodiCar();
        } else if (name.equals("baoma")) {
            return new BaomaCar();
        }
        return null; }}Copy the code

It can be seen from the above that the simple factory mode violates the open closed principle, and the if branching logic of the core factory class needs to be modified for each new model added. In fact, our usual application is mainly based on specific business scenarios. For example, there are only three types of your products, which are fully satisfied by simple factories. There is no need to do excessive design.

1.2. Factory method pattern

1.2.1 definition

Factory Method, also known as polymorphic Factory pattern.

Define an interface for creating an object,but let subclasses decide witch class to instantiate. Factory Method lets a class defer instantiation to subclasses. In the factory method pattern, the core factory class is no longer responsible for all product creation, but subclasses do the specific creation. The core class becomes an abstract factory role, responsible only for giving the interface that a concrete factory subclass must implement, without touching the details of which product class should be instantiated

Abstract product class, concrete product can have more than one, inherit the abstract product

Abstract factory class, responsible for defining the production of product objects.

There are specific factory classes to implement how a product generates objects.

We can renovate the simple factory above

1.3. Abstract the factory pattern

1.3.1 defining

  • Abstract Factory pattern is a common design pattern.

Provider an interface for creating families of relate or dependent objects without specifying their concrete classes. Provides an interface for creating a set of related or interdependent objects without specifying their concrete classes.

2. Builder mode

2.1 define

Build patterns are also called builder patterns. Separate the construction of complex object from its representation so that the same construction process can create different representations. Is to separate the construction of a complex object from its representation, so that the same construction process can be created in different ways.

There are four roles in builder mode

    1. Builder: Provides an abstract interface that regulates the construction of the components of a product object. This interface specifies which parts of a complex object to implement and does not involve the creation of specific object parts.
    1. ConcreteBuilder: realize the interface Builder, for different business logic, specific parts of a complex object creation. Provide an example of the product after the construction process is complete.
    1. Director: Calls the specific builder to create the parts of a complex object. The Director does not involve product information, but is responsible for ensuring that the parts of the object are created in their entirety or in some order.
    1. Product: The complex object to create.

2.2 Application Scenarios

For example, in our common tool class, the thread pool in the HuTool package is created using the builder mode.

  1. The objects that need to be generated have complex internal structures.
  2. The internal properties of the objects that need to be generated are themselves interdependent.

2.3 Code Cases

Creating a thread pool this way is clear and error-free for the user. The above is based on huTool for thread pool secondary encapsulation, in fact, this idea of our own middleware some binary library package can adopt this design pattern.

3. Singletons

3.1 define

A Singleton Pattern is a relatively simple design Pattern. Ensure a class has only one instance,and provide a gloable point of access to it. Make sure there is only one instance of a class, and instantiate it yourself and provide the entire instance to the entire system.

3.2 Application Scenarios

  1. The counter of the website is generally implemented using the singleton pattern, otherwise it is difficult to synchronize.
  2. Application of the log application, generally is a singleton pattern implementation, only one instance to operate is good, otherwise the content is not good to append display.
  3. Thread pools with multiple threads are also designed in a singleton mode, because thread pools are designed to facilitate the control of the threads in the pool
  4. Windows is a typical singleton, it can’t open two
  5. Windows is also a typical singleton application. Only one instance of the recycle bin is maintained throughout the operation of the system.

3.3 Singleton creation methods

  1. The hungry type
  2. LanHanShi
  3. Static inner class
  4. The enumeration
  5. DCL singleton pattern

3.3 Code Cases

4. Prototype patterns

4.1 define

Prototype Pattern Specify the kinds of objects to create using a prototypical instance, and create new objects by copying the prototype. Specify the type of class to create with prototype instances, and create new objects by copying these prototypes.

4.2 Application Scenarios

  1. Class initialization consumes a large number of resources, including data, hardware resources, and so on. At this point we can avoid these costs by copying prototypes.
  2. When an object generated by new requires a lot of data preparation or permissions, you can use the prototype pattern.
  3. When an object needs to be made available to other objects and each caller may need to change its value, consider copying multiple objects for the caller to use using the archetype pattern, known as protective copying.

The multiple examples in the Spring framework are the prototyping patterns used.

Usage:

  • Implement the Cloneable interface
  • Override the Clone method in the Object class.

Prototype patterns are divided into shallow copy and deep copy

4.3 Code Cases

AdvTemplate Activity notification template

public class AdvTemplate {

    private String subject = "National Day Lucky Draw of XXX Bank";

    private String context = "National Day Lucky Draw Notice";

    public String getContext() {
        return context;
    }
    public String getSubject() {
        returnsubject; }}Copy the code

Mail class

@Data
public class Mail implements Cloneable {

    /** * Mail recipient */
    private String receiver;

    /** * Theme */
    private String subject;

    /** * nickname */
    private String nickName;

    /** * Content */
    private String context;

    /** * End */
    private String tail;

    public Mail(AdvTemplate template) {
        this.context = template.getContext();
        this.subject = template.getSubject();
    }

    @Override
    public Mail clone() {
        Mail mail = null;
        try {
            mail = (Mail) super.clone();
        } catch (Exception e) {

        }
        returnmail; }}Copy the code

There is a potential pit when copying, the default reference type is shallow copy, so we need to be careful when writing colone.

reference

The Zen of Design Patterns

For other examples in code, see my Github example at github.com/liuyichun/d…