One article summarizes three design patterns (23 design patterns)

Yesterday we introduced the seven principles of design patterns, and today we introduce the three specific categories of design patterns and 23 specific design patterns.

Overview

Three design patterns

The three design patterns are: creation, structure, and behavior

  • Creation mode is mainly used to describe how to create objects (5 types)
  • The structural pattern is mainly used to describe how to realize the combination of classes or objects (7 types)
  • Behavioral patterns are mainly used to describe how classes or objects interact and how to assign responsibilities (11 types)

The mind map is as follows:

image

Pay attention to the public account: java Toka Fox, reply [Design Mode] to get the original high-definition picture. Thank you for your attention.

Creation mode

Singleton mode

A design pattern in which objects are created only once in memory.

Hungry Chinese
public class Singlenton{
    // 只实例化一次
    private final static Singleton INSTANCE = new Singleton();
    // 私有构造方法,防止被实例化
    private Singleton(){}
    public static Singleton getInstance(){
        return INSTANCE;   
    }
}
Lazy (double check)
public class Singleton{
    // 使用volatile修饰,让变量每次使用的时候从主存主取而不是从各个线程的“工作内存”中
    private static volatile Singleton instance;
    // 私有构造方法,防止被实例化
    private Singleton(){}
    public static Singleton getInstance(){
        if(instance == null){
            synchronized(Singleton.class){
                if(instance == null){
                    instance = new Singleton;   
                }
            }
        }
        return instance;
    }
}
Static inner class pattern
public clsaa Singleton{
    // 私有构造方法,防止被实例化
    private Singleton(){}
    // 使用一个内部类来维护单例,只有在改类被加载的时候,才会实例化对象
    private static class SingletonInstance{
        private static final Singleton INSTANCE = new Singleton();
    }
    // 获取实例
    public static Singleton getInstance(){
        return SingletonInstance.INSTANCE;
    }
}
  • The upgraded version of the hungry man model solves the problem of waste of resources and also ensures thread safety; the object is instantiated only when the inner class is loaded; compared to the lazy man, the static inner class method avoids queuing in Synchronization block makes null judgment, and the performance is better than that of lazy man mode, it is recommended to use
Enumeration mode
public enum Singleton{
    INSTANCE;
    public Singleton getInstance(){
        return INSTANCE;
    }
}
  • Thread safety. JVM guarantees thread safety and single instance. In reflection and serialization scenarios, single instance can still be guaranteed.

Factory mode

Simple engineering mode

Create a unified factory class, create different objects according to the parameters passed in, you need to select one of the products in a bunch of products.

Factory mode

The factory pattern does not use a unified factory class to manage all objects, but each object has a different factory corresponding to it

Abstract factory pattern

The abstract factory pattern is a further optimization of the factory pattern. The factory class can not only create one object, but also create a group of objects

The simple factory pattern is to pass values ​​in from outside to obtain different objects

The abstract factory pattern obtains objects directly through methods without passing values

Builder mode

Separate the construction of a complex object from its representation, so that the same construction process can create different representations.

That is, only the necessary parameters are passed during construction, and other parameters are optionally passed in through the set method.

Description
  • Create a static inner class Builder in the class, and then copy the parameters in the class to the Builder class
  • Create a private constructor in the class, the parameter is of type Builder
  • Create a setting function in the Builder, assign values ​​to those optional parameters in the class, and the return value is an instance of the Builder type
  • Create a build() method in the Builder, build an instance of the class in it and return it.

Prototype mode

Use prototype instances to specify the types of objects to be created, and create new objects by copying these prototypes. Prototype mode is an object creation mode.

Structural model

Adapter mode

The purpose is to adapt the interface

Class adaptation
  • There is an existing class that will be adapted
public class Adaptee{
    public void adapteeRequest(){
        System,out,println("被适配者的方法");
    }
}
  • Define a target interface
public interface target{
    void request();
}
  • Through the adapter, implement the interface inheritance class, and then call the parent class method.

Decorator mode

The decoration mode allows to add new functions to an existing object without changing its structure. This type of design pattern belongs to the structural pattern, which serves as a wrapper for an existing class.

Dynamically add functions.

Agency model

In the proxy model, one class represents the function of another class. This type of design pattern belongs to the structural pattern; in the proxy pattern, we create objects with existing objects in order to provide functional interfaces to the outside

Mainly divided into static proxy and dynamic proxy

Appearance mode

The appearance mode hides the complexity of the system and provides an interface for the client to access the system. This type of design pattern is a structural pattern, which adds an interface to the existing system to hide the complexity of the system

This model involves a single class that provides simplified methods for client requests and delegated calls to existing system class methods

The appearance mode is to put their relationship in a Facade class, which reduces the degree of coupling between classes.

Bridge mode

Bridging is used to decouple abstraction and realization so that the two can be changed independently. By providing a bridge structure before abstraction and realization, the decoupling of the two is realized.

This mode involves an interface as a bridge, making the three-dimensional function independent of the interface implementation class. These two types of classes can be structurally changed without affecting each other.

Combination mode

It is used to treat a group of similar objects as a single object. The combination mode combines objects according to a tree structure, which is used to represent part and overall levels. This type of design pattern is a structural pattern. It creates a tree structure of object combination

Created a class that contains its own object group. This class provides a way to modify the same object group

Flyweight model

Mainly used to reduce the number of objects created to reduce memory usage and improve performance. This type of design pattern is a structural pattern, which provides a way to reduce the number of objects to improve the object structure required by the application

Try to reuse existing objects of the same kind, and if no matching object is found, create a new object.

Behavioral model

Strategy mode and state mode

Same point
  • By splitting the behavior and state into a series of small components, the function is replaced by the condition and state, which is more in line with the principle of opening and closing, and is easy to expand. In addition, both can be used as an alternative to if else or branch; the largest support Behavior and status are limited
difference
  • In the strategy mode, the function of the class is to actively change according to the current conditions
  • In state mode, the function of the class is passively changed from the current state
  • There is no correlation between each behavior or algorithm in the strategy mode
  • There is a correlation between the states in the state pattern, and the state itself

Interpreter mode

Provides a way to evaluate the grammar or expression of the language. This pattern implements an expression interface that interprets a specific context. This mode is used in SQL parsing, symbol processing engines, etc.

Observer mode

When there is a one-to-many relationship between objects, the observer mode is used. For example, when an object is modified, it will automatically notify the dependent objects

Intermediary model

The intermediary pattern is used to reduce the complexity of communication between multiple objects and classes. This mode provides an intermediary class, which usually handles the communication between different classes, supports loose coupling, and makes the code easy to maintain

Memo mode

Save a certain state of an object in order to restore the object at an appropriate time.

Command mode

Command mode is a data-driven design mode. The request is wrapped in the object in the form of a command and passed to the calling object. The calling object looks for a suitable object that can handle the command, and passes the command to the corresponding object, which executes the command.

Chain of Responsibility Model

A chain of recipient objects is created for the request. This mode gives the type of request and decouples the sender and receiver of the request.

Visitor mode

We use a visitor class, which changes the execution algorithm of the element class. In this way, the execution algorithm of the element can be changed as the visitor changes. This type of design pattern is a behavioral pattern. According to the mode, the element object has received the visitor object so that the visitor object can handle operations on the element object.

Iterator mode

It is a design pattern commonly used in java and .net programming environments. This mode breeds sequential access to the elements of the collection object without knowing the underlying representation of the collection object.

Template method pattern

An abstract class publicly defines the way/template to execute its methods. Its subclasses can be implemented by overriding methods as needed, but the call will be made in the way defined in the abstract class.

At last

  • If you feel that you are rewarded after reading it, I hope to give me a thumbs up. This will be the biggest motivation for me to update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

——I am Chuhu, and I love programming as much as you.

image

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/111353707