Design pattern learning notes -- overview, creative pattern

Design mode

summary

significance

The essence of design pattern is the practical application of object-oriented design principles. It is a full understanding of the encapsulation, inheritance and polymorphism of classes, as well as the association and composition of classes

Basic elements

  1. name

    1. Question: the application environment of this mode.
    2. Solution: it includes the components of the design, the relationship between them, their respective responsibilities and cooperation methods. The solution does not describe a specific and specific design or implementation, but provides an abstract description of the design problem and how to solve the problem with a general element combination (combination of classes or objects).
    3. Effect: the application effect of the mode and the problem that should be weighed when using the mode, that is, the advantages and disadvantages of the mode.

Classification of design patterns

  • Classification according to purpose
  • According to the scope of action
Scope \ purposeCreate modeStructural modeBehavioral model
Class modeFactory method(class) adapterTemplate method and interpreter
Object modeSingleton, prototype, abstract factory, builderAgent, (object) adapter, bridge, decoration, appearance, element sharing, combinationPolicy, command, responsibility chain, status, observer, mediator, iterator, visitor, memo

Create mode

Pay attention to how to create objects. By separating the creation and use of objects, the system coupling is reduced, and users do not need to know the details of object creation.

1, Singleton mode

definition

A pattern in which a class has only one instance and the class can create the instance itself.

The singleton mode has three features:

  1. A singleton class has only one instance object;
  2. The singleton object must be created by the singleton class itself;
  3. The singleton class provides a global access point for accessing the singleton.

Advantages and disadvantages

advantage
  • Singleton mode can ensure that there is only one instance in memory and reduce the memory overhead.
  • Multiple occupation of resources can be avoided.
  • The global access point is set in the singleton mode, which can optimize and share the access of resources.
shortcoming
  • Expansion difficulty
  • Concurrent testing is not conducive to code debugging
  • It is easy to violate the principle of single responsibility

realization

1, Lazy mode

The singleton is created only when the call occurs

public class Lazy{
    private static volatile Lazy instance = null; //synchronization
    
    private Lazy(){} //Private constructor to avoid external instantiation
    
    public static synchronized Lazy getInstance(){
        //synchronization
        if(instance == null){
            instance = new Lazy();
        }
        return instance;
    }
}

Multithreaded programs need to add volatile and synchronized keywords to ensure thread safety

##### shortcoming

On the premise of ensuring thread safety, each access needs to be synchronized, which will affect performance and consume more resources

2, Hungry man model

Once the class is loaded, this singleton will be created and will not be changed to ensure thread safety

public class Hungry{
    private static final Hungry instance = new Hungry();
    
    private Hungry(){}
    
    public static Hungry getInstacne(){
        return instance;
    }
}

2, Prototype

definition

Using an instance that has been created as a prototype, create a new object that is the same or similar to the prototype by copying the prototype object.

Creating objects through prototype mode does not need to know the details of object creation, which is very efficient

advantage
  • Java The built-in prototype mode is based on the replication of memory binary stream, and its performance is better than that of directly new an object.
  • You can use deep cloning to save the state of the object, and use prototype mode to copy the object and save its state, which simplifies the process of creating the object for use when needed (for example, restoring to a certain state in History), and can assist in the implementation of undo operation.
shortcoming
  • You need to configure a clone method for each class
  • clone method is located inside the class. When modifying an existing class, you need to modify the code, which violates the opening and closing principle.
  • When implementing deep cloning, you need to write more complex code, and when there are multiple nested references between objects, in order to implement deep cloning, the classes corresponding to each layer of objects must support deep cloning, which will be troublesome to implement. Therefore, deep cloning and shallow cloning need to be used properly.

realization

  • Shallow cloning: create a new object. The properties of the new object are exactly the same as the original object. For non basic type properties, it still points to the memory address of the object pointed to by the original property.
  • Deep clone: when a new object is created, other objects referenced in the attribute will also be cloned and no longer point to the original object address.
structure
  • Abstract prototype class
  • Specific type class
  • Access class
Concrete implementation

Shallow cloning

class Realizetype implements Cloneable{
    Realizetype(){
        System.out.printly("Prototype class created successfully");
    }
    
    public Object clone() throws CloneNotSupportedException {
        System.out.println("Copy successful");
        return (Realizetype) super.clone();
    }
}

Application scenario

  • Objects are the same or similar, that is, when only several individual attributes are different.
  • The cost of creating objects is large, such as long initialization time, too much CPU, or too much network resources. Resources need to be optimized.
  • Creating an object requires cumbersome data preparation or access rights, and needs to improve performance or security.
  • This kind of object is widely used in the system, and each caller needs to re assign its properties.

3, Simple factory mode - > static factory mode

definition

The simple factory pattern has a specific factory class that can generate multiple different products

advantage
  1. The factory class contains the necessary logical judgment to decide when to create an instance of which product. The client can be exempted from the responsibility of directly creating product objects, and it is very convenient to create corresponding products. The responsibilities of factories and products are clearly distinguished.
  2. The client does not need to know the class name of the specific product created, but only needs to know the parameters.
  3. You can also import configuration files to replace and add new specific product classes without modifying the client code.
shortcoming
  1. The factory class of simple factory mode is single, which is responsible for the creation of all products. The responsibility is too heavy. Once it is abnormal, the whole system will be affected. Moreover, the factory class code will be very bloated and violate the principle of high aggregation.
  2. Using simple factory mode will increase the number of classes in the system (introducing new factory classes), and increase the complexity and understanding difficulty of the system
  3. It is difficult to expand the system. Once new products are added, the factory logic has to be modified. When there are many product types, the logic may be too complex
  4. The simple factory mode uses the static factory method, which makes the factory role unable to form a hierarchical structure based on inheritance.

realization

structure
  • Simple factory: it is the core of the simple factory pattern and is responsible for implementing the internal logic of creating all instances. The method of creating product class of factory class can be directly called by the outside world to create the required product object.
  • Abstract Product: it is the parent class of all objects created by a simple factory and is responsible for describing the common interface shared by all instances.
  • Specific products: it is the creation goal of simple factory mode.
public class Client {
    public static void main(String[] args) {
    }
    //Abstract product
    public interface Product {
        void show();
    }
    //Specific product: ProductA
    static class ConcreteProduct1 implements Product {
        public void show() {
            System.out.println("Specific product 1 display...");
        }
    }
    //Specific product: ProductB
    static class ConcreteProduct2 implements Product {
        public void show() {
            System.out.println("Specific product 2 display...");
        }
    }
    final class Const {
        static final int PRODUCT_A = 0;
        static final int PRODUCT_B = 1;
        static final int PRODUCT_C = 2;
    }
    static class SimpleFactory {
        public static Product makeProduct(int kind) {
            switch (kind) {
                case Const.PRODUCT_A:
                    return new ConcreteProduct1();
                case Const.PRODUCT_B:
                    return new ConcreteProduct2();
            }
            return null;
        }
    }
}

Application scenario

For the case of relatively few product types, consider using the simple factory mode. The client using the simple factory mode only needs to pass in the parameters of the factory class, and does not need to care about the logic of how to create objects. It can easily create the required products.

4, Factory mode

definition

Define a factory interface for creating product objects, and postpone the actual creation of product objects to specific sub factory classes

---->Create and use separate

The advantage of further abstracting the simple factory mode is that the system can introduce new products without modifying the original code, that is to meet the opening and closing principle

advantage
  • Users only need to know the name of the specific factory to get the desired product, without knowing the specific creation process of the product.
  • Flexibility is enhanced. For the creation of new products, you only need to write one more corresponding factory class.
  • Typical decoupling framework. The high-level module only needs to know the abstract class of the product, does not need to care about other implementation classes, and meets the Demeter rule, the dependency inversion principle and the Richter substitution principle.
shortcoming
  • The number of classes is easy to be too many, which increases the complexity
  • It increases the abstraction and understanding difficulty of the system
  • Abstract products can only produce one product, which can be used Abstract factory pattern solve.

realization

structure
  1. Abstract Factory: it provides an interface for creating products, through which the caller accesses the factory method newProduct() of a specific factory to create products.

  2. Concrete factory: it mainly realizes the abstract methods in the abstract factory and completes the creation of specific products.

  3. Abstract Product: it defines the specification of the Product and describes the main characteristics and functions of the Product.

  4. Concrete product: it implements the interface defined by the abstract product role and is created by the specific factory. It corresponds to the specific factory one by one.

    public class AbstractFactoryTest {
        public static void main(String[] args) {
            try {
                Product a;
                AbstractFactory af;
                af = (AbstractFactory) ReadXML1.getObject();
                a = af.newProduct();
                a.show();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
    //Abstract product: provides the interface of the product
    interface Product {
        public void show();
    }
    //Concrete product 1: implement abstract methods in abstract products
    class ConcreteProduct1 implements Product {
        public void show() {
            System.out.println("Specific product 1 display...");
        }
    }
    //Concrete product 2: implement abstract methods in abstract products
    class ConcreteProduct2 implements Product {
        public void show() {
            System.out.println("Specific product 2 display...");
        }
    }
    //Abstract factory: provides the generation method of factory products
    interface AbstractFactory {
        public Product newProduct();
    }
    //Specific factory 1: the generation method of factory products is realized
    class ConcreteFactory1 implements AbstractFactory {
        public Product newProduct() {
            System.out.println("Specific factory 1 generation-->Specific products 1...");
            return new ConcreteProduct1();
        }
    }
    //Specific factory 2: the generation method of factory products is realized
    class ConcreteFactory2 implements AbstractFactory {
        public Product newProduct() {
            System.out.println("Specific factory 2 generation-->Specific products 2...");
            return new ConcreteProduct2();
        }
    }
    

Application scenario

  • The customer only knows the name of the factory that created the product, but does not know the specific product name. Such as TCL TV factory, Hisense TV factory, etc.
  • The task of creating objects is completed by one of multiple concrete sub factories, while the abstract factory only provides the interface to create products.
  • Customers don't care about the details of creating products, they only care about the brand of products

4, Abstract factory pattern

definition

It is a pattern structure that provides an interface for the access class to create a group of related or interdependent objects, and the access class can obtain different levels of products of the same family without specifying the specific class of the product

realization

The structure of the abstract factory pattern is similar to that of the factory method pattern, except that there is more than one product type, so there is more than one method to create products

interface AbstractFactory {
    public Product1 newProduct1();
    public Product2 newProduct2();
}
class ConcreteFactory1 implements AbstractFactory {
    public Product1 newProduct1() {
        System.out.println("Specific factory 1 generation-->Specific products 11...");
        return new ConcreteProduct11();
    }
    public Product2 newProduct2() {
        System.out.println("Specific factory 1 generation-->Specific products 21...");
        return new ConcreteProduct21();
    }
}

Application scenario

  1. When the objects to be created are a series of interrelated or interdependent product families, such as televisions, washing machines, air conditioners, etc.
  2. There are multiple product families in the system, but only one of them is used at a time. If someone only likes to wear clothes and shoes of a certain brand.
  3. The class library of products is provided in the system, and the interfaces of all products are the same. The client does not depend on the creation details and internal structure of product instances.

5, Builder mode

definition

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

Build complex objects, decompose them into multiple simple objects and build them step by step

advantage
  • Good encapsulation and separation of construction and representation
  • Good expansibility, conducive to decoupling
  • The client does not need to know the composition details. The builder can refine the creation process without affecting other modules
shortcoming
  • Product components must be the same
  • If the product changes internally, the builder also needs to modify it

The builder pays attention to the assembly process of a product and the factory pays attention to the creation of parts. The two can be used together

realization

structure
  1. Product role: it is a complex object containing multiple components, and its components are created by specific builders.
  2. Abstract Builder: it is an interface that contains abstract methods for creating various sub parts of a product, and usually includes a method getResult() that returns a complex product.
  3. Concrete Builder: implement the builder interface and complete the specific creation method of each component of complex products.
  4. Director: it calls the component construction and assembly methods in the builder object to complete the creation of complex objects. The director does not involve the information of specific products.
Concrete implementation

product

class Product {
    private String partA;
    private String partB;
    private String partC;
    public void setPartA(String partA) {
        this.partA = partA;
    }
    public void setPartB(String partB) {
        this.partB = partB;
    }
    public void setPartC(String partC) {
        this.partC = partC;
    }
    public void show() {
        //Displays the characteristics of the product
    }
}

Abstract builder

abstract class Builder {
    //Create product object
    protected Product product = new Product();
    public abstract void buildPartA();
    public abstract void buildPartB();
    public abstract void buildPartC();
    //Return product object
    public Product getResult() {
        return product;
    }
}

Specific builder

public class ConcreteBuilder extends Builder {
    public void buildPartA() {
        product.setPartA("build PartA");
    }
    public void buildPartB() {
        product.setPartB("build PartB");
    }
    public void buildPartC() {
        product.setPartC("build PartC");
    }
}

Commander

class Director {
    private Builder builder;
    public Director(Builder builder) {
        this.builder = builder;
    }
    //Product construction and assembly method
    public Product construct() {
        builder.buildPartA();
        builder.buildPartB();
        builder.buildPartC();
        return builder.getResult();
    }
}

Customer class

public class Client {
    public static void main(String[] args) {
        Builder builder = new ConcreteBuilder();
        Director director = new Director(builder);
        Product product = director.construct();
        product.show();
    }
}

Application scenario

  • The same method and different execution order produce different results.
  • Multiple assemblies or parts can be assembled into one object, but the results are different.
  • The product class is very complex, or different call sequences in the product class have different effects.
  • Initializing an object is particularly complex, with many parameters, and many parameters have default values.

Difference between builder mode and factory mode

  • The builder pattern pays more attention to the calling sequence of methods, and the factory pattern pays more attention to the creation of objects.
  • The intensity of creating objects is different. The builder mode creates complex objects, which are composed of various complex parts. The objects created by the factory mode are the same
  • The focus is different. The factory mode only needs to create the object, while the builder mode should not only create the object, but also know what parts the object is composed of.
  • The builder mode is different according to the order in the construction process, and the component composition of the final object is also different.

Keywords: Java Programming Database Design Pattern Interview

Added by gowni on Mon, 31 Jan 2022 22:10:52 +0200