Common design patterns

Posted by dlester on Fri, 21 Jan 2022 14:01:22 +0100

Classification of design patterns

Generally speaking, design patterns are divided into three categories:

There are five kinds of creation patterns: factory method pattern, abstract factory pattern, singleton pattern, builder pattern and prototype pattern.

There are seven structural modes: adapter mode, decorator mode, agent mode, appearance mode, bridge mode, combination mode and sharing mode.

There are eleven behavioral modes: strategy mode, template method mode, observer mode, iteration sub mode, responsibility chain mode, command mode, memo mode, status mode, visitor mode, mediator mode and interpreter mode.

Seven principles of design pattern

Single responsibility principle: the responsibility of a class should be single, and too many responsibilities should not be placed in one class
Opening and closing principle: software entities are open for external expansion, but closed for internal modification, that is, expand their functions without modifying a software entity
Richter substitution principle: in a software system, where a base class object can be accepted, a subclass object must be accepted
Dependency Inversion Principle: program for the abstract layer, not for specific classes
Interface isolation principle: use a special interface to replace a unified interface
Composite Reuse Principle: the relationship between composition and aggregation association should be used as much as possible in the system, and inheritance relationship should be used as little or even not as much as possible
Dimitri's Law: the fewer references a software entity has to other entities, the better. Or if two classes do not communicate directly with each other, the two classes should not interact directly, but indirectly by introducing a third party

Common design patterns

1, Simple factory model

Definition: return different kinds of instances according to different parameters. The simple factory mode specifically defines a class to be responsible for creating instances of other classes. The created classes usually have a common parent class. The point is that when you need something, you only need to pass in a correct parameter to get the object you need without knowing its creation details.

Instance resolution:
Abstract product class: interface TV {public void play();}
Specific product category:

class HaierTV implements TV{

    @Override
    public void play() {
        System.out.println("Haier TV playing...");
    }
}
class TCLTV implements TV{

    @Override
    public void play() {
        System.out.println("TCL TV playing...");
    }
}

Factory type:
Factory class is the core of the whole system and provides static factory methods.
Auxiliary code: the addition of configuration file is required

class TVfatoy{
     public static  TV produceTV(String band) throws Exception{
         if (band.equalsIgnoreCase("Haier")){
             System.out.println("The TV factory produces Haier TV sets");
             return new HaierTV();
         }else if (band.equalsIgnoreCase("TCL")){
             System.out.println("production TCL Television");
             return new TCLTV();
         }else{
             throw  new Exception("sorry,Temporarily unable to produce this brand");
         }
     }
}

advantage:
1 contains the necessary logical judgment, realizes the division of responsibility, and provides a special factory class for creating objects
2 the client does not need to know the class name, but only the parameters corresponding to the specific product class
3 by introducing the configuration file, the flexibility of the system is improved by replacing and adding new specific product classes without modifying any client code
Disadvantages:
1. A product problem affects the overall situation
2 increase the number of classes, increase the complexity and understanding difficulty of the system, and the system expansion is difficult, which is not conducive to the expansion and maintenance of the system
3 due to the use of static factory, the factory role cannot form a hierarchical structure based on inheritance
Applicable environment:
1. The factory class is responsible for creating fewer objects, which will not cause too complex business logic in the factory method
2 the client only knows the parameters passed into the factory. It doesn't care about how to create the object. It doesn't care about the details. It only needs to know the parameters corresponding to the type.
Mode application:
1. Simple factory mode is widely used in JDK class library
2 Java encryption technology, symmetric encryption technology and asymmetric encryption technology

2, Factory method model

**Definition: * * factory method mode, also known as factory mode, also known as virtual constructor mode or polymorphic factory mode, belongs to class creation mode. In this mode, the factory parent class is responsible for defining the public interface for creating product objects and generating specific product objects. The purpose is to delay the instantiation of product classes to factory subclasses, Determine which specific product class should be instantiated through the factory subclass (create objects through Java reflection).
Instance resolution:
Abstract product class:

interface TV{
     public void play();
}

Specific product category:

class HaierTV implements TV{

    @Override
    public void play() {
        System.out.println("Haier TV playing...");
    }
}
class TCLTV implements TV{

    @Override
    public void play() {
        System.out.println("TCL TV playing...");
    }
}

Abstract factory class:

interface TVfactory{
     public TV produce();
}

Specific plant type:

class HaierTVFactory implements TVfactory{

    @Override
    public TV produce() {
        System.out.println("Haier TV factory produces Haier TV sets..");
        return  new HaierTV();
    }
}
class TCLTVFactory implements TVfactory{

    @Override
    public TV produce() {
        System.out.println("TCL The TV factory produces Haier TV sets..");
        return  new TCLTV();
    }
}

Auxiliary code: XML configuration file
advantage:
1. Users only need to care about the factory corresponding to the product, do not need to care about the creation details, or even know the class name of the specific product class
Polymorphic design based on factory role and product role is the key of its model
3 when adding new products, there is no need to modify the interface provided by the abstract factory and abstract products, and the scalability of the system has been improved, which fully conforms to the opening and closing principle
Disadvantages:
1 add new products to write specific product classes, which increases the complexity of the system and will bring additional overhead to the system
2 due to the scalability of the system involved, the abstract layer needs to be introduced. DOM, reflection and other technologies may be encountered during implementation, which increases the difficulty of system implementation.
Applicable environment:
A class does not know the class of the object it needs. It only needs to know the corresponding factory. Collective products are created by the corresponding class
2 which object does a class create through its subclasses
3 delegate the task of creating objects to one of multiple factory subclasses, and specify dynamically when necessary. The specific class name can be stored in the configuration file or database.
Mode application:
1. iterator() method in Java collection framework
2 Java Message Service JMS
3 a large number of factory method patterns are also used in JDBC

3, Abstract factory pattern

**Definition: * * provides interfaces for creating a series of related or interdependent objects without specifying their classes. The abstract factory pattern is also called kit pattern, which belongs to object creation pattern.
Hierarchical structure of products: the inheritance structure of products. The popular understanding is that TV festivals can be divided into many brands
Product family: different products from the same factory. Generally speaking, a TCL factory can produce televisions, refrigerators and other electrical appliances
The popular understanding of this model is: there are several factories that can produce televisions, refrigerators and other electrical appliances, but they have their own brands, depending on which brand and what you want to buy.
Instance resolution:
Abstract product class:

interface TV{//Television
     public void play();
}
interface AirConditioner{//Air conditioning
     public  void  changeTem();
}

Specific product category:

lass HaierTV implements TV{//Television

    @Override
    public void play() {
        System.out.println("Haier TV playing...");
    }
}
class TCLTV implements TV{

    @Override
    public void play() {
        System.out.println("TCL TV playing...");
    }
}
//Air conditioning
class HaierConditioner implements AirConditioner{

    @Override
    public void changeTem() {
        System.out.println("Haier air conditioner changing temperature....");
    }
}
class TCLConditioner implements AirConditioner{

    @Override
    public void changeTem() {
        System.out.println("TCL Air conditioning changing temperature....");
    }
}

Abstract factory class:

interface EFfactory{
     public TV produceTV();
     public  AirConditioner produceAirC();
}

Specific plant type:

class HaierFactory implements EFfactory{//Haier factory

    @Override
    public TV produceTV() {
        return  new HaierTV();
    }

    @Override
    public AirConditioner produceAirC() {
        return new HaierConditioner();
    }
}
class TCLTFactory implements EFfactory{//TCL factory

    @Override
    public TV produceTV() {
        return  new HaierTV();
    }

    @Override
    public AirConditioner produceAirC() {
        return new TCLConditioner();
    }
}

Auxiliary code: XML configuration file
advantage:
1 isolate the generation of specific classes, so that customers do not need to know what is created. Due to this isolation, it is easier to create a factory, realizing the purpose of high cohesion and low coupling.
2 when multiple design objects in a product family are designed to work together, it can ensure that the client always uses only the objects in the same product family
3 it is convenient to add new specific factories and product families, which conforms to the opening and closing principle.
Disadvantages:
When adding new product objects, it is difficult to extend the abstract factory to produce new kinds of products. If extended, it will have a great impact on subclasses.
Applicable environment:
1 there is more than one product family in the system, and only one product family is used at a time.
2. Products belonging to the same product family have common constraints when used together
The system provides a library of product classes. All products are implemented with the same interface, so that the client does not depend on the specific implementation.
Mode application:
Abstract factory pattern is used in AWT (Abstract window toolkit) of Java language.
2. When changing the page theme and requiring changes with the buttons, text boxes, background colors, etc. in the page, you can use the abstract factory pattern design.
Difference from the factory pattern: the factory method aims at the time hierarchical structure, while the abstract factory needs to face multiple hierarchical structures
Abstract factory pattern extension:
1. Inclination of opening and closing principle:
1) The product family is added and the abstract factory pattern well supports the opening and closing principle without modifying the existing code
2) Add a new product hierarchy: you need to modify all factory roles, including abstract factory classes, because you need to add methods to produce new products, which can not well support the opening and closing principle. This is the inclination of the abstract factory opening and closing principle.
2 degradation of plant mode:
Abstract factory mode each concrete class only creates a new product object, that is, when there is only one product hierarchy, it degenerates into factory mode. When factory mode and abstract factory are combined with concrete factory and provided to a unified factory to create product object, and its creation method design is called static method, It further degenerates into a simple factory model.

4, Singleton mode

definition:
Ensure that a class has only one instance, and instantiate it by itself and provide this instance to the whole system. This class is called a singleton class. There are three important points: a class can only have one instance. You must create this instance yourself and provide this instance to the whole system. Singleton mode includes only one singleton role.
Instance resolution:
The implementation process of singleton mode should pay attention to the following three points: the constructor of singleton class is private, providing its own static private member variable and a public static factory method.
This paper mainly introduces the hungry type singleton class and the lazy type singleton class
Hungry Han style single instance class (the class, as its name suggests, should be loaded immediately. If you are hungry, you should eat immediately)

class EagerSingleton{//Hungry Han type singleton
    private static final  EagerSingleton instance = new EagerSingleton();
    private EagerSingleton(){}
    public  static  EagerSingleton getInstance(){
        return  instance;
    }
}

Lazy singleton

class LazySingleton{//Lazy singleton
    private  static  LazySingleton instance = null;
    private LazySingleton(){}
    synchronized  public static LazySingleton getInstance(){
        if(instance==null)
            instance = new LazySingleton();
        return  instance;
    }
}

advantage:
1 provides controlled access to unique instances because a singleton class encapsulates its unique instance
2 since there is only one object in the system memory, resources can be saved. For some frequently destroyed and created objects, singleton mode can improve the performance of the system.
3 allow variable instances
Disadvantages:
Because there is no abstraction layer in the singleton pattern, it is very difficult to expand the singleton class
2. The responsibility of single instance class is too heavy, which violates the principle of single responsibility to a certain extent
3. The negative problems caused by abusing singleton can save resources. Designing database connection objects as singleton classes may lead to too many programs sharing connection pool objects and connection pool overflow.
Applicable environment:
1. The system only needs one instance object
2. Only one public access point is allowed for a single instance of the client calling class. It cannot be accessed through other channels except the public access point
The necessary condition for using singleton mode is that singleton mode should be used only when there is only one instance of a class in a system.
Problems needing attention:
1. Do not use singleton mode to access global variables, which is contrary to the intention of singleton mode. It is better to put the global variables in the static members of Van Gogh's corresponding class
2. Do not take the database connection as a single example, because a system may have multiple connections to the database, and if there is a connection pool, release the connection as soon as possible
Mode application:
1 there are many singleton patterns in the Java language library JDK, such as Java Lang.runtime class
2. In the Java EE framework of the primary key number generator, spring will create bean classes through singleton mode

5, Adapter mode

Structural mode description:
Structural patterns can describe two different things: classes and instances of classes, that is, objects. According to this, structural patterns can be divided into class structural patterns and object structural patterns. Generally, there is only inheritance and implementation relationship in class structural patterns, and object structural patterns care about the combination of classes and objects.
definition:
Convert the interface of a class into another interface desired by the user, so that those classes that cannot work together due to incompatible interfaces can work together without modifying the internal structure of existing things. It can be used as either class structure type or object structure type. Generally speaking, a converter can connect mobile phones and computers, similar to a data cable
Usage requirements: the original adapter interface and the interface of the abstract target class cannot be modified
Instance resolution:
Target abstract class:

interface  Robot{
    public  void cry();
    public  void move();
}

Adapter class:

class  dog{
    public  void wang(){
        System.out.println("The dog barked...");
    }
    public  void run(){
        System.out.println("Dog, run...");
    }
}

Adapter class (core equivalent to Middleware):

class  DogAdapter extends  dog implements Robot{

    @Override
    public void cry() {
        System.out.println("Robot imitation:");
        super.wang();
    }

    @Override
    public void move() {
        System.out.println("Robot imitation ");
        super.run();
    }
}

Client test class:

  public static void main(String[] args) {
       Robot robot = (Robot) XMLUtils.getBean();
       robot.cry();
       robot.move();
    }

Auxiliary code: xml configuration file
advantage:
1 decouple the adapter class of the target class, and reuse the existing adapter class by introducing an adapter without an original code
2. It increases the transparency and reusability of the class, encapsulates the specific implementation in the adapter class, and improves the reusability of the adapter for the client
3. The flexibility and scalability are very good. The adapter can be easily replaced by changing the configuration file
Advantages of class 4 adapters: the adapter class is a subclass of the adapter class. Some adapter methods can be replaced in the adapter class, making it more flexible
5 advantages of object adapter: different adapters can be adapted to a target, that is, the same adapter can adapt the adapter class and its subclasses to the target interface
Disadvantages:
Disadvantages of class adapter: it does not support multiple inheritance, so at most one adapter class can be adapted at a time, and the target abstract class can only be an interface, which has certain limitations
Disadvantages of object adapter: it is not easy to replace the methods of adapter class. If you want to replace, the implementation process is more complex
Applicable environment:
1. The system needs to use existing classes, and the interfaces of these classes do not meet the needs
There is no significant correlation between the two categories
Mode application:
1. JDBC database connection tool
2 three notification types of spring AOP framework
Extension: default adapter mode and bidirectional adapter mode

6, Decorator mode

The way to add behavior to a class and object: inheritance mechanism and association mechanism. Generally speaking, use inheritance less and association mechanism as much as possible. The main advantages of association relationship will not destroy the encapsulation of the class
definition:
Dynamically add some extra responsibilities to an object. In terms of increasing the function of the object, the decoration mode is more flexible than generating subclasses
Generally speaking, it is to add some beauty to your original gorgeous appearance and make you a more handsome (beautiful) person
Instance resolution:
Abstract component class:

interface  Transform{
    public void move();
}

Concrete component class: decorated object

final  class  Car implements Transform{
    public Car(){
        System.out.println("Transformers are a car");
    }
    @Override
    public void move() {
        System.out.println("Moving on land...");
    }
}

Abstract decoration class (core): Decoration by what

class  Change implements  Transform{
    private Transform transform;

    public Change(Transform transform) {
        this.transform = transform;
    }

    @Override
    public void move() {
        transform.move();
    }
}

Specific decoration: how to decorate

class  Robot extends  Change{

    public Robot(Transform transform) {
        super(transform);
        System.out.println("Become a robot...");
    }
    public  void say(){
        System.out.println("Talk: the people who read this article are handsome men and beautiful women...");
    }
}
class  Airplane extends Change{

    public Airplane(Transform transform) {
        super(transform);
        System.out.println("Become a plane");
    }
    public  void fly(){
        System.out.println("Random flying...");
    }
}

Client test class:

public static void main(String[] args) {
    Transform camaro = new Car();
    camaro.move();
    Robot bum = new Robot(camaro);
    bum.move();
    bum.say();
}

advantage:
1 decoration patterns can provide more flexibility than inheritance relationships
2. The function of an object can be extended dynamically, and different decorators can be selected through configuration files to realize different behaviors
3 create many different behavior combinations to get more powerful objects
4. Specific components and collective decoration can be changed independently, and the original code does not need to be changed, which conforms to the opening and closing principle
Disadvantages:
1. Generate many small objects, increase the complexity of the system, and increase the difficulty of learning and understanding
2 decoration mode is more error prone than inheritance, and troubleshooting is very difficult and cumbersome
Applicable environment:
1 add responsibilities to a single object in a dynamic and transparent manner without affecting other objects
2 dynamic increase and dynamic revocation
3. When the system cannot be extended by inheritance or inheritance is not conducive to system expansion and maintenance: there are a large number of independent extensions. In order to support each combination, subclasses grow explosively, and class definitions cannot be inherited (final class)
Mode application:
The most classic example is Java IO
Mode extension:
Simplification: the interface of the decorated class must be the same as that of the decorated class. Don't put too much logic and state in the specific component class. There is only one specific component class and no abstract component class
Transparent and translucent decorative patterns:
Transparency: client programs should not declare concrete build types and concrete decoration classes, but should all declare Abstract build types
Translucency: enhance the function of the original class without changing the interface
Most decorative patterns are translucent rather than completely transparent

7, Agent mode

definition:
One of the commonly used structural design patterns is to provide a proxy for an object, and the proxy object controls the reference to the original object. The popular one will be an intermediary
Instance resolution:·
Abstract topic role (Abstract permission class):

interface  AbstarctPer{
    public  void modifUserInfo();
    public  void viewNote();
    public  void publishNote();
    public  void modifyNote();
    public void setLevel(int level);
}

Real subject role (real permission class):

class  RealPer implements  AbstarctPer{

    @Override
    public void modifUserInfo() {
        System.out.println("Modify user information");
    }

    @Override
    public void viewNote() {

    }

    @Override
    public void publishNote() {
        System.out.println("Post new posts");
    }

    @Override
    public void modifyNote() {
        System.out.println("Modify post content");
    }

    @Override
    public void setLevel(int level) {

    }
}

Proxy subject role (core permission proxy class):

class  per implements  AbstarctPer{
    private  RealPer realPer = new RealPer();
    private  int level =0;
    @Override
    public void modifUserInfo() {
        if(0==level){
            System.out.println("Sorry, you don't have the permission...");
        }else if (1==level){
            realPer.modifUserInfo();
        }
    }

    @Override
    public void viewNote() {
        System.out.println("View Post");
    }

    @Override
    public void publishNote() {
        if(0==level){
            System.out.println("Sorry, you don't have the permission...");
        }else if (1==level){
            realPer.publishNote();
        }
    }

    @Override
    public void modifyNote() {
        if(0==level){
            System.out.println("Sorry, you don't have the permission...");
        }else if (1==level){
            realPer.modifyNote();
        }
    }

    @Override
    public void setLevel(int level) {
        this.level = level;
    }
}

Auxiliary code: xml configuration file
advantage:
1 coordinate the caller and callee to a certain extent, and reduce the coupling degree of the system to a certain extent
2 the remote agent can access objects on the remote machine, has better computing performance and processing speed, and can quickly process client requests
3 virtual agent uses a small object to represent a large object, reduces the consumption of system resources, optimizes the system and improves the running speed
4. The protection agent can control the permission to use real objects
Disadvantages:
Due to the addition of proxy objects between the client and the real subject, some types of proxy modes may slow down the processing speed of requests
2. The implementation of agent mode requires additional work, and the implementation of some agent modes is very complex
Applicable environment:
Remote agent, virtual agent, copy on write agent, protection agent, buffer agent, firewall agent, synchronization agent and intelligent reference agent. Among them, virtual agent, remote agent and protection agent are the most common agent modes
Mode application:
Java RMI, EJB,Web Service and other distributed technologies, Spring AOP technology
Several common agent modes
1 picture agent: it controls the browsing of large pictures. You can get them when you need them. The real pictures are loaded into the background through agent technology combined with multithreading, which does not affect the browsing of foreground pictures
2 remote agent: it can hide the details of the network, so that customers do not have to consider the existence of the network
3 virtual agent: it is suitable for virtual agent that consumes resources, but it is also a practice of exchanging time for space
4 dynamic proxy: a typical application is Spring AOP
Key: the key of dynamic Proxy lies in the dynamic generation of dynamic Proxy class at runtime through InvocationHandler and Proxy media. The generated dynamic Proxy class still implements the Subject interface and calls back the invoke method of InvocationHandler implementation class when calling method. The invoke method of InvocationHandler implementation class calls back the corresponding method of the Proxy entity through reflection.

8, Observer mode

definition:
Define a one to many dependency between objects, so that whenever an object state changes, its related dependent objects are notified and automatically updated. Is an object behavior pattern. Popular will be that you are a spy. You stare at a target. When the target wants to leave, you keep up. Of course, you are not the only spy. The observer pattern is applied in the current popular MVC architecture.
Instance resolution:
Abstract target class:

abstract  class  mySubject{
    protected ArrayList observers= new ArrayList();
    //Registration method
    void attach(MyObserve observe ){
        observers.add(observe);
    }
    void detach(MyObserve observe){
       observers.remove(observe);
    }
    abstract  void cry();
}

Abstract Observer class:

interface  MyObserve{
    void response();//Abstract response method
}

Specific target class: observed

class  Cat extends  mySubject{

    @Override
    void cry() {
        System.out.println("Cat barking");
        for (Object obs:observers) {
            ((MyObserve)obs).response();
        }
    }
}

Specific observers: Observers

class  mouse implements  MyObserve{

    @Override
    public void response() {
        System.out.println("The mouse tried to escape");
    }
}
class  Dog implements MyObserve{

    @Override
    public void response() {
        System.out.println("The dog barked");
    }
}

Customer test class:

public static void main(String[] args) {
    mySubject subject = new Cat();
    MyObserve obs1,obs2,obs3;
    obs1 = new mouse();
    obs2 = new mouse();
    obs3 = new Dog();
    subject.attach(obs1);
    subject.attach(obs2);
    subject.attach(obs3);
    subject.cry();
}

advantage:
1. It can realize the separation of presentation layer and data logic layer, and a stable message update transmission mechanism
An abstract coupling is established between the observation target and the observer
3 the observer mode supports broadcast communication, and the observation target will send a notice to all registered observers, which simplifies the difficulty of system design
4 meet the requirements of opening and closing principles
Disadvantages:
1 if there are multiple direct or indirect observers of an observation target, it will take a lot of time to inform all observers
2 if there is a circular dependency between the observation target and the observation object, the system may crash
3 can't tell the observer how the observation target changes, just inform it that it has changed
Applicable environment:
In the abstract model, one aspect depends on another
2. The change of an object leads to the change of one or more objects. When we don't know how many objects have changed, the coupling between systems can be reduced
An object must notify other objects without knowing who they are
Observer mode can also create a chain trigger mechanism
Mode application and extension:
Application: delegate event model DEM, Java language parsing technology
Extensions: Java language support for Observer mode (Observable class and Observer interface) and MVC mode

Topics: Java Design Pattern