Vernacular explanation design patterns (11 common)

Posted by Trip1 on Wed, 19 Jan 2022 09:06:44 +0100

Design patterns (11 common)

Seven principles

Single principle

One class, one responsibility

Opening and closing principle

Expand opening and modify closing

Richter substitution

As a supplement to the principle of opening and closing, where the father appears, the subclass can certainly appear

Principle: Abstract implementation

Dependence Inversion Principle

Dependent interface, complementary dependent implementation, i.e. Abstract Programming, decoupling

Interface isolation principle

Different interfaces cannot be in different interfaces, so as to avoid unnecessary dependencies between interfaces

Synthesis / aggregation Reuse Principle

Do something by introducing (injecting) objects instead of inheriting classes

Dimitt's law

Reduce the interaction and dependence of objects and make modules independent

Single column mode (important)

Create pattern

Lazy (thread safe)

public class Singleton2 {

    private static Singleton2 instance;

    private Singleton2() {}

    public static synchronized Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }

        return instance;
    }

}

Hungry Han (thread safe)

public class Singleton3 {

    private static Singleton3 instance = new Singleton3();

    private Singleton3() {}

    public static Singleton3 getInstance() {
        return instance;
    }

} 

Double check lock / double check lock + volatile keyword

public class Singleton7 {

    private static volatile Singleton7 instance = null;

    private Singleton7() {}

    public static Singleton7 getInstance() {
        if (instance == null) {
            synchronized (Singleton7.class) {
                if (instance == null) {
                    instance = new Singleton7();
                }
            }
        }
        return instance;
    }
}

Static inner class implementation

The static inner class is unique in the JVM, which ensures the singleton characteristics

public class Singleton{
    private static class SingletonHolder{
        private static final Singleton INSTANCE=new Singleton();
    }
    private Singleton(){
        
	}
    public static final Singleton getInstance(){
		return SingletonHolder.INSTANCE;
    }
}

Factory mode

Create pattern

Intention: define an interface for creating objects, let its subclasses decide which factory class to instantiate, and the factory mode delays the creation process to the subclasses

ShapeFactory shapeFactory = new ShapeFactory();

        //Get the object of Circle and call its draw method
        Shape shape1 = shapeFactory.getShape("CIRCLE");
        //Call Circle's draw method
        shape1.draw();

        //Get the object of Rectangle and call its draw method
        Shape shape2 = shapeFactory.getShape("RECTANGLE");
        //Call the draw method of Rectangle
        shape2.draw();

        //Get the Square object and call its draw method
        Shape shape3 = shapeFactory.getShape("SQUARE");
        //Call Square's draw method
        shape3.draw();

Abstract factory pattern

Abstract interface factory, also known as super factory, implements interfaces to create different factory objects, and factory objects create different objects

Observer mode

Behavioral model

Intent: defines a one to many dependency between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated

Decorator mode

Structural model

Intent: dynamically add some additional responsibilities to an object. In terms of adding functionality, decorator pattern is more flexible than generating subclasses

Decoration mode is mainly passed into subclass objects through construction methods. IO system is just a method of using decoration mode to decorate and enhance the parent class

The difference between decorator and polymorphism

  • Polymorphism can be coerced, and if you point to the parent class, you can only use the methods of the parent class, not the methods unique to the child class
  • The decorator passes parameters through the constructor. Polymorphism is a dynamic binding

The difference between decorator pattern and inheritance

Enhanced classes implemented by inheritance:
Advantages: clear code structure and simple implementation
Disadvantages: for each class that needs to be enhanced, specific subclasses should be created to help enhance it, which will lead to too large inheritance system.

Enhanced classes implemented by decoration mode:
Advantages: multiple classes that need to be enhanced can be enhanced internally through polymorphism technology
Disadvantages: you need to maintain instances of classes that need to be enhanced internally through polymorphism technology. This makes the code a little more complex.

Builder pattern

Complex objects are created separately. After the components are created, the components are assembled into the required complex objects

Prototype mode

Call the clone () of the prototype (implement the clonable interface) or other means to create the object

Shallow replication

Simple copy creation of the target class

public object clone(){//Override clone() of interface clonable
    return (Target class)super.clone();
}

Deep replication

The properties of the target class will also be type copied and created

public object clone(){//Override clone() of interface clonable
    Target class object= (Target class)super.clone();
    object.attribute=(Attribute type)this.attribute.clone();
}

Adapter mode

Do not modify the original code structure (class structure) to friendly complete the docking of various systems

  • Class adapter mode
  • Object Adapter Pattern
  • Interface adapter mode

proxy pattern

The object and the target object are not suitable or can not be accessed directly. They need to be accessed through a proxy object

Forward proxy: targeted (select the specified one)

Reverse proxy: the purpose is the same, but the object is not necessarily the same

Visitor mode

Separate data structures from operations on data

Intermediary model

The application of the seventh principle (Demeter's law) is to supplement the direct interaction between objects, and realize the interaction between objects through intermediaries

Topics: Java Design Pattern Interview