36 design pattern learning notes

Posted by sonofsam on Sun, 23 Jan 2022 19:35:33 +0100

                Design pattern learning notes

1. Introduction to design mode

​ 1. Design patterns should be learned and applied flexibly, not mechanically.

If you want to use design patterns easily, you need to lay a solid foundation of programming language, consolidate your own programming ideas, accumulate a lot of practical experience and improve development ability. The purpose is to make the program low coupling, high reuse, high cohesion, easy to expand and easy to maintain.

​ 2. Analyze successful pattern application projects

Analyzing the existing application examples is a good way to learn. We should pay attention to learning the existing projects, not only how to realize the design pattern, but also where to use the design pattern.

​ 3. Understanding patterns in programming

Software development is a practical work, and the most direct method is programming. There is no go master who has never played chess but is familiar with the set pattern, and there is no precedent that he can become an architecture designer without programming. Mastering design patterns is a natural thing. In addition to the accumulation of theory and practice, you may "gradually realize" or "suddenly realize".

​ 4. Avoid over design

Design pattern solves the problem of insufficient design, but at the same time, it should avoid excessive design. Be sure to keep in mind the principle of simplicity and know that the design pattern is to make the design simple, not more complex. If the introduction of design patterns makes the design complex, we can only say that we complicate the simple problem, and the problem itself does not need design patterns.

There are seven design principles in the design pattern, which are opening and closing principle, Richter substitution principle, dependency inversion principle, single responsibility principle, interface isolation principle, Dimiter principle and synthesis Reuse Principle.

In fact, the purpose of these principles is only one: reduce the coupling between objects and increase the reusability, scalability and maintainability of programs.

Memory formula: access plus restrictions, functions should be frugal, dependencies are not allowed, interfaces should be added dynamically, parent classes should be abstract, and extensions should not be changed.

In programming, we should minimize the program function and do only one thing for each class. If you add new functions based on similar functions, you should make rational use of inheritance. For the call of multiple methods, we should be able to use the interface, and reasonably set the function and quantity of the interface. Finally, low coupling and high cohesion are achieved between classes.

1. Singleton mode

2. Factory method

3. Abstract Factory

4. Responsibility chain model

5. Formwork method ok

In general, template method + policy mode are used together.

I Introduction to template method

In the process of object-oriented programming, programmers often encounter this situation: when designing a system, they know the key steps required by the algorithm and determine the execution order of these steps, but the specific implementation of some steps is still unknown, or the implementation of some steps is related to the specific environment.

For example, when you go to a bank to handle business, you generally go through the following four processes: number retrieval, queuing, handling specific business, scoring bank staff, etc. among them, the business of number retrieval, queuing and scoring bank staff is the same for each customer and can be implemented in the parent class, but the specific business varies from person to person. It may be deposit Withdrawal or transfer can be deferred to subclasses.

There are many such examples in life. For example, a person will get up, eat, do things, sleep, etc. the content of "doing things" may be different every day. We define these instances that specify the process or format as templates, allowing users to update them according to their own needs, such as resume templates, thesis templates, template files in Word, etc.

The template method pattern described below will solve the above similar problems.

II Definition and characteristics of pattern

The definition of Template Method pattern is as follows: define the algorithm skeleton in an operation, and delay some steps of the algorithm to the subclass, so that the subclass can redefine some specific steps of the algorithm without changing the structure of the algorithm. It is a kind of behavioral model.

The main advantages of this mode are as follows.

​ 1. It encapsulates the invariant part and extends the variable part. It encapsulates the algorithm that is considered to be the invariant part into the parent class, and inherits the variable part algorithm from the subclass, which is convenient for the subclass to continue to expand.

​ 2. It extracts part of the common code from the parent class to facilitate code reuse.

Some methods are implemented by subclasses, so subclasses can add corresponding functions through extension, which conforms to the opening and closing principle.

The main disadvantages of this mode are as follows:

1. It is necessary to define a subclass for each different implementation, which will increase the number of classes, make the system larger and the design more abstract, and indirectly increase the complexity of the system implementation.

2. The abstract method in the parent class is implemented by the subclass, and the execution result of the subclass will affect the result of the parent class, which leads to a reverse control structure, which improves the difficulty of code reading.

3. Due to the shortcomings of the inheritance relationship itself, if a new abstract method is added to the parent class, all subclasses must be changed.

III Structure and implementation of pattern

The template method pattern needs to pay attention to the cooperation between abstract classes and concrete subclasses. It uses the polymorphism technology of virtual functions and the reverse control technology of "don't call me, let me call you". Now let's introduce their basic structure.

1. Structure of the model

The template method pattern contains the following main roles:

1.1 Abstract Class / abstract template

Abstract template class, which is responsible for giving the outline and skeleton of an algorithm. It consists of a template method and several basic methods.

These methods are defined as follows:

Template method: defines the skeleton of the algorithm and calls its basic methods in a certain order.

Basic method: it is a step in the whole algorithm, including the following types:

​ . Abstract method: declared in an abstract class and implemented by a concrete subclass.

​ . Concrete method: it has been implemented in an abstract class and can be inherited or overridden in a concrete subclass.

​ . Hook method: it has been implemented in abstract classes, including logical methods for judgment and empty methods that need to be overridden by subclasses.

1.2 Concrete Class

The concrete implementation class implements the abstract methods and hook methods defined in the abstract class, which are a constituent step of a top-level logic.

The structure diagram of template method mode is shown in Figure 1:

IV What is the template method pattern

The so-called template method mode is actually very simple. It can be considered from the perspective of template. It is an application of template, just like the teacher's test paper. Everyone's test paper is the same, that is, they are copied from the teacher's original test paper. This original test paper is a template, but everyone's answers written on the test paper are different. This is the template method mode, Is it easy to understand. Its main purpose is to move the invariant behavior from subclasses to superclasses, and remove the duplicate code in subclasses.

Template method defines the skeleton of an algorithm in operation, and delays some steps to subclasses, so that subclasses can redefine some specific steps of an algorithm without changing the structure of the algorithm. UML structure diagram is as follows:

AbstractClass implements a template method, which defines the skeleton of the algorithm, and the specific subclass will redefine the PrimitiveOperation to implement the steps of an algorithm; ConcreteClass implements PrimitiveOperation to complete the steps related to specific subclasses in the algorithm.

1. Abstract template class

Define a template method to combine PrimitiveOperation1() and PrimitiveOperation2() to form an algorithm, and then let the subclass redefine the two methods.

public abstract class AbstractClass {
 
 public abstract void PrimitiveOperation1();
 public abstract void PrimitiveOperation2();
 
 //Template method
 public void TemplateMethod() {
          PrimitiveOperation1();
          PrimitiveOperation2();
 }
}

2. Specific templates

Here, two concrete template classes, ConcreteClassA and ConcreteClassB, are defined to test, inherit the abstract template class and implement specific methods.

public class ConcreteClassA extends Abstract Class {
 
@Override
 public void PrimitiveOperation1() {
 	System.out.println("Specific method A Method 1 implementation");
 }
 
@Override
 public void PrimitiveOperation2() {
	System.out.println("Specific method A Method 2 implementation");
  }
}

3.Client

Different results are obtained by calling the template method.

public class Client {
 
 public static void main(String[] args) {
 
 Abstract Class abstractClass;
 
 abstractClass = new ConcreteClassA();
    abstractClass.TemplateMethod();
 
 abstractClass = newConcreteClassB();
	abstractClass.TemplateMethod();
  }
  
 }

The operation results are as follows:

V Application of template method

1. When to use

​ . There are some general methods

2. Method

​ . Abstract the general algorithm

3. Advantages

​ . Encapsulate invariant part

​ . Extract the common part code for easy maintenance

​ . The behavior is controlled by the parent class and implemented by the child class

4. Disadvantages

​ . Each different implementation requires a subclass implementation, resulting in an increase in the number of classes and a larger system

5. Usage scenario

. There are methods shared by multiple subclasses, and the logic is the same

. Important and complex methods can be considered as template methods

. During refactoring, the template method pattern is a frequently used pattern, which extracts the same code into the parent class and constrains its behavior through hook functions

6. Application examples

. The questions are the same, but the answers are different

. For cars, the order from starting to stopping is the same, except for engine sound, whistle sound, etc

. When building a house, the foundation, wiring and water pipes are the same, and there are differences only in the later stage of construction

7. Precautions

. In order to prevent malicious operations, the general template methods are added with the final keyword

Vi demo

1.Game abstract class

package com.tangguanlin.templatemethod;
import lombok.extern.slf4j.Slf4j;
/**
 * Game abstract class
 */
@Slf4j
public abstract class Game {

    //Game name
    abstract String getName();

    //Template method initialization
    public final void init() {
      log.info("game {} Initialization complete",getName());
    }

    //Game start
    abstract void start();
    //game over
    abstract void over();

    //Template
    public final void play() {
        init();
        start();
        over();
    }
}

2. Super Mario concrete implementation class

package com.tangguanlin.templatemethod;
import lombok.extern.slf4j.Slf4j;
/**
 * Super Mario concrete implementation class
 */
@Slf4j
public class Mario extends Game{
    private static final String NAME = "Super Mario";

    @Override
    String getName() {
        return NAME;
    }

    @Override
    void start() {
        log.info("1player In place");
        log.info("2player In place");
        log.info("game {} start---------------------------", NAME);
    }

    @Override
    void over() {
        log.info("1player Eaten by cannibals");
        log.info("2player Drop pit");
        log.info("game {} end---------------------------", NAME);
    }
}

3. Specific implementation of hero alliance

package com.tangguanlin.templatemethod;
import lombok.extern.slf4j.Slf4j;
/**
 * Hero alliance implementation class
 */
@Slf4j
public class LOL extends Game {

    private static final String NAME = "League of Heroes";

    @Override
    String getName() {
        return NAME;
    }

    @Override
    void start() {
        log.info("Red disabled hero over");
        log.info("The blue side disabled the hero. Over");
        log.info("Galen is in position");
        log.info("Ash is in position");
        log.info("Rez is in position");
        log.info("Kyle is in position");
        log.info("Yi is in place");
        log.info("game {} start---------------------------", NAME);
    }

    @Override
    void over() {
        log.info("The front teeth were destroyed");
        log.info("The crystal was destroyed");
        log.info("game {} end---------------------------", NAME);
    }
}

4. Client

package com.tangguanlin.templatemethod;
/**
 *  client
 */
public class Client {

    public static void main(String[] args) {
        Game game = new LOL();
        game.play();

        Game mario = new Mario();
        mario.play();
    }
}

VII Project practice

It encapsulates the abstract method of approval process. Due to the requirements of new approval process and the previous modules call different interfaces and operate different databases, it is generally difficult to handle the added approval functions uniformly. The template method is a good choice

1. Abstract template class

First define an abstract class of approval process,

Abstract methods include:

  1. Update the release status (the data of the corresponding module is updated to the release status after the approval is successful)

  2. Update unpublished status (in case of approval failure, approval process deletion, etc., update the data of the corresponding module to published status)

  3. Batch update unpublished status (in case of batch deletion of approval process, the data of the corresponding module is in published status)

  4. Get the menu id (query whether the module has an approval process according to the menu id)

2. Specific templates

6. Strategy mode ok

6.1 introduction to strategic mode

In Strategy Pattern, the behavior of a class or its algorithm can be changed at run time.

This type of design pattern belongs to behavioral pattern.

In the policy pattern, we create objects representing various policies and a context object whose behavior changes with the change of policy objects.

The policy object changes the execution algorithm of the context object.

6.2 definition and characteristics of mode

**Intent: * * define a series of algorithms, encapsulate them one by one, and make them replaceable.

**Main solutions: * * when there are many similar algorithms, it is complex and difficult to maintain when using if... else.

**When to use: * * a system has many classes, and what distinguishes them is their direct behavior.

**How to solve: * * encapsulate these algorithms into classes one by one and replace them arbitrarily.

**Key code: * * implement the same interface.

Application example:

1. Zhuge Liang's knapsack, each knapsack is a strategy.

2. The way of travel, choose to ride a bike or take a car. Each way of travel is a strategy.

3. LayoutManager in JAVA AWT.

advantage:

1. The algorithm can be switched freely.

2. Avoid using multiple conditional judgment.

3. Good expansibility.

Disadvantages: 1. The number of policy classes will increase.

2. All policy classes need to be exposed.

Usage scenario:

1. If there are many classes in a system, the only difference between them is their behavior,

Then using the policy pattern can dynamically make an object choose one behavior among many behaviors.

2. A system needs to dynamically select one of several algorithms.

3. If an object has a lot of behaviors, without appropriate patterns, these behaviors can only be realized by multiple conditional selection statements.

**Note: * * if a system has more than four policies, you need to consider using mixed mode to solve the problem of policy class expansion.

Usage scenario:

We will create a Strategy interface that defines activities and an entity policy class that implements the Strategy interface.

Context is a class that uses a certain strategy. StrategyPatternDemo,

Our demo class uses Context and policy objects to demonstrate the behavior of Context when the policy it configures or uses changes.

6.3 demo1

1.Payment interface

package com.tangguanlin.strategy1;
/**
 * Payment abstract class
 **/
public interface Payment {

    /**
     * payment
     * @param money
     */
    void pay(int money);
}

2. Bank payment realization

package com.tangguanlin.strategy1.service;
import com.tangguanlin.strategy1.Payment;

/**
 * Specific types of bank payment
 **/
public class BankPayService implements Payment {
    @Override
    public void pay(int money) {
        System.out.println("Using bank payment, amount:"+money);
    }
}

3. Alipay payment implementation class

package com.tangguanlin.strategy1.service;
import com.tangguanlin.strategy1.Payment;

/**
 * Alipay payment category
 **/
public class AlipayService implements Payment {
    @Override
    public void pay(int money) {
        System.out.println("Payment is being made using Alipay."+money);
    }
}

4. Wechat payment implementation

package com.tangguanlin.strategy1.service;
import com.tangguanlin.strategy1.Payment;
/**
 * Specific categories of wechat payment
 **/
public class WechatService implements Payment {
    @Override
    public void pay(int money) {
        System.out.println("Using wechat payment, amount:"+money);
    }
}

5. Client call

package com.tangguanlin.strategy1;
import com.tangguanlin.strategy1.service.AlipayService;
import com.tangguanlin.strategy1.service.BankPayService;
import com.tangguanlin.strategy1.service.WechatService;
import java.util.HashMap;
import java.util.Map;

/**
 * Client call
 **/
public class Test {
    private static Map<String, Payment> paymentMap = new HashMap<>();

    static {
        paymentMap.put("alipay", new AlipayService());
        paymentMap.put("wechatPay", new WechatService());
        paymentMap.put("bank", new BankPayService());
    }

    public static void main(String[] args) {

        Payment payment = getPayWay("alipay");
        payment.pay(10);
    }

    //Get payment method
    public static Payment getPayWay(String payType){
        return paymentMap.get(payType);
    }
}

6.4 demo2

1. Operation interface class

package com.tangguanlin.strategy2;
/**
 * Description: operation interface class
 * Author: Tang Guanlin
 * Date: 17:00 on October 31, 2021
 */

public interface Operation {
    public int doOperation(int num1, int num2);
}

2. Addition operation implementation class

package com.tangguanlin.strategy2;
/**
 * Description: addition operation
 * Author: Tang Guanlin
 * Date: 17:00 on October 31, 2021
 */

public class OperationAdd implements Operation{
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

3. Subtraction implementation class

package com.tangguanlin.strategy2;
/**
 * Description: subtraction
 * Author: Tang Guanlin
 * Date: 17:00 on October 31, 2021
 */
public class OperationSubtract implements Operation{
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

4. Multiplication implementation class

package com.tangguanlin.strategy2;

/**
 * Description: multiplication
 * Author: Tang Guanlin
 * Date: 17:00 on October 31, 2021
 */
public class OperationMultiply implements Operation{
    @Override
    public int doOperation(int num1, int num2) {
        return num1 * num2;
    }
}

5.OperationContext class

package com.tangguanlin.strategy2;

/**
 * Description: Context class
 * Author: Tang Guanlin
 * Date: 18:00 on October 31, 2021
 */
public class OperationContext {
    private Operation operation;

    public OperationContext(Operation operation){
        this.operation = operation;
    }

    public int executeOperation(int num1, int num2){
        return operation.doOperation(num1, num2);
    }
}

6. Client call

package com.tangguanlin.strategy2;
/**
 * Description: client call
 * Author: Tang Guanlin
 * Date: 18:00 on October 31, 2021
 */
public class OperationClient{

    public static void main(String[] args) {
        //Addition operation
        OperationContext operationContext = new OperationContext(new OperationAdd());
        System.out.println("10 + 5 = " + operationContext.executeOperation(10, 5));

        //Subtraction operation
        operationContext = new OperationContext(new OperationSubtract());
        System.out.println("10 - 5 = " + operationContext.executeOperation(10, 5));

        //Multiplication
        operationContext = new OperationContext(new OperationMultiply());
        System.out.println("10 * 5 = " + operationContext.executeOperation(10, 5));
    }
}

7. Builder mode ok

Builder

7.1 demand for housing projects

​ 1. Need to build a house: this process is piling, cutting walls and capping

​ 2. There are all kinds of houses, such as ordinary houses, high-rise buildings, villas. Although the process of all kinds of houses is the same, the requirements are not the same.

​ 3. Please write a program to complete the requirements.

7.2 analysis of traditional methods and ideas

The traditional method is actually the template method design mode:

7.3 traditional code implementation

The traditional method is actually the template method design pattern

Project structure:

AbstructHouseBuilder.java Abstract builder

package com.tangguanlin.design_pattern.builder.history;
/**
 * Description: Abstract construction class - template method
 * Author: Tang Guanlin
 * Date: 14:00, January 21, 2022
 */
public abstract class AbstructHouseBuilder {

    //Laying foundation
    public abstract  void buildBasic();

    //Cut wall
    public abstract  void buildWall();

    //Capping
    public abstract void roofed();

    //Building formwork method
    public void build(){
        buildBasic();
        buildWall();
        roofed();
    }
}

CommonHouseBuilder.java ordinary house construction

package com.tangguanlin.design_pattern.builder.history;
/**
 * Description: specific construction of ordinary houses
 * Author: Tang Guanlin
 * Date: 14:00, January 21, 2022
 */
public class CommonHouseBuilder extends AbstructHouseBuilder {
    @Override
    public void buildBasic() {
        System.out.println("Laying foundation for ordinary house");
    }

    @Override
    public void buildWall() {
        System.out.println("Ordinary house wall cutting");
    }

    @Override
    public void roofed() {
        System.out.println("Ordinary house capping");
    }
}

HouseBuilder.java tall building construction

package com.tangguanlin.design_pattern.builder;
/**
 * Description: tall building builder
 * Author: Tang Guanlin
 * Date: 11:00, January 21, 2022
 */
public abstract class HouseBuilder {

    public  House house =  new House();

    //Write the construction process and abstract method
    public abstract  void buildBasic(); //Laying foundation

    public abstract void buildWall();   //Cut wall

    public abstract void buildRoofed();  //Make a roof

    //Build the house and return it
    public House returnHouse(){

        return  house;
    }
}

Client.java client

package com.tangguanlin.design_pattern.builder.history;
/**
 * Description: client
 * Author: Tang Guanlin
 * Date: 14:00, January 21, 2022
 */
public class Client {
    public static void main(String[] args) {

        //Ordinary house
        CommonHouseBuilder commonHouse = new CommonHouseBuilder();
        //Build an ordinary house
        commonHouse.build();

        System.out.println("-----------------");

        //Tall buildings
        HighHouseBuilder highHouse = new HighHouseBuilder();
        //Building tall buildings
        highHouse.build();
    }
}

Operation results:

Laying foundation for ordinary house
 Ordinary house wall cutting
 Ordinary house capping
-----------------
High building foundation
 High building foundation
 High building foundation

7.4 advantages and disadvantages of traditional methods

​ 1. The advantages are easy to understand and easy to operate

​ 2. The designed program structure is too simple, the cache layer object is not designed, and the program expansion and maintenance are not good,

In other words, this design scheme encapsulates the product (i.e. house) and the creation process (i.e. house building process), and the coupling is enhanced.

​ 3. Solution: decouple product and product construction process = = > builder mode

7.5 basic introduction of builder mode

Builder

1. Builder mode, also known as generator mode, is an object construction mode. It can abstract the construction process of complex objects (abstract categories),

So that different implementation methods of this abstract process can construct objects with different representations (properties).

2. Builder mode is to create a complex object step by step. It allows users to build complex objects only by specifying their types and contents,

Users do not need to know the specific build details inside it.

7.6 four roles of builder mode

1. Product role: a specific product object

2. Abstract Builder: create the interface / abstract class specified by each part of a Product object

3. Specific Builder: realize the interface, build and assemble various components

4. Commander: build an object using Builder interface. It is mainly used to create a complex object.

It has two main functions:

First, it isolates the production process of customers and objects

Second, be responsible for controlling the production process of product objects

7.7 schematic class diagram of builder mode

Director Commander: This is the buffer layer

7.8 the builder mode solves the building demand

Train of thought analysis (class diagram):

7.9 builder mode code implementation

Code structure:

House.java house -- > Product

package com.tangguanlin.design_pattern.builder;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * Description: product house -- > Product
 * Author: Tang Guanlin
 * Date: 11:00, January 21, 2022
 */

@NoArgsConstructor
@AllArgsConstructor
@Data
public class House {
     private String basic;  //foundation
     private String wall;   //wall
     private String roofed;  //roof
}

AbstructHouseBuilder.java Abstract builder

package com.tangguanlin.design_pattern.builder;
/**
 * Description: Abstract builder
 * Author: Tang Guanlin
 * Date: 11:00, January 21, 2022
 */
public abstract class AbstructHouseBuilder {

    public  House house =  new House();

    //Write the construction process and abstract method
    public abstract  void buildBasic(); //Laying foundation

    public abstract void buildWall();   //Cut wall

    public abstract void buildRoofed();  //Make a roof

    //Build the house and return it
    public House returnHouse(){

        return  house;
    }
}

CommonHouseBuilder.java ordinary house specific builder

package com.tangguanlin.design_pattern.builder;
/**
 * Description: specific builders of ordinary houses
 * Author: Tang Guanlin
 * Date: 11:00, January 21, 2022
 */
public class CommonHouseBuilder extends AbstructHouseBuilder {
    @Override
    public void buildBasic() {
        System.out.println("The foundation of an ordinary house is 5m");
    }

    @Override
    public void buildWall() {
        System.out.println("Ordinary house wall cutting 10 cm");
    }

    @Override
    public void buildRoofed() {
        System.out.println("Cut wall roof of ordinary house");
    }
}

HighHouseBuilder. Specific builder of Java high-rise building

package com.tangguanlin.design_pattern.builder;
/**
 * Description: specific builder of high-rise building
 * Author: Tang Guanlin
 * Date: 11:00, January 21, 2022
 */
public class HighHouseBuilder extends AbstructHouseBuilder {
    @Override
    public void buildBasic() {
        System.out.println("The foundation of high-rise building is 100m");
    }

    @Override
    public void buildWall() {
        System.out.println("High building wall cutting 20 cm");
    }

    @Override
    public void buildRoofed() {
        System.out.println("The transparent roof of a tall building");
    }
}

HouseDirector. The Java commander specifies the production process here and returns the product core class

package com.tangguanlin.design_pattern.builder;

/**
 * Note: the commander specifies the production process here and returns the product core class
 * Author: Tang Guanlin
 * Date: 11:00, January 21, 2022
 */
public class HouseDirector {
    AbstructHouseBuilder houseBuilder = null;

    //Constructor passed into houseBuilder
    public HouseDirector(AbstructHouseBuilder houseBuilder){
        this.houseBuilder = houseBuilder;
    }

    //Pass in houseBuilder through the set method
    public void setHouseBuilder(AbstructHouseBuilder houseBuilder){
        this.houseBuilder = houseBuilder;
    }

    //How to deal with the process of building a house and give it to the commander. Here you specify the production process of the product
    public House BuilderHouse(){
        houseBuilder.buildBasic();  //Lay the foundation first
        houseBuilder.buildWall();  //Re cut the wall
        houseBuilder.buildRoofed();  //Final capping
        return  houseBuilder.returnHouse();
    }
}

Client.java builder mode client

package com.tangguanlin.design_pattern.builder;
/**
 * Description: Builder mode client
 * Author: Tang Guanlin
 * Date: 11:00, January 21, 2022
 */
public class Client {
    public static void main(String[] args) {

        //Build an ordinary house
        CommonHouseBuilder commonHouseBuilder = new CommonHouseBuilder();

        //Generate the commander who created the house
        HouseDirector houseDirector = new HouseDirector(commonHouseBuilder);

        //Finish building the house and return to the product
        House commonHouse = houseDirector.BuilderHouse();

        System.out.println("-----------------------------------------------");

        //Build a tall building
        HighHouseBuilder highHouseBuilder = new HighHouseBuilder();
        houseDirector.setHouseBuilder(highHouseBuilder);
        House highHouse = houseDirector.BuilderHouse();
    }
}

Operation results:

The foundation of an ordinary house is 5m
 Ordinary house wall cutting 10 cm
 Cut wall roof of ordinary house
-----------------------------------------------
The foundation of high-rise building is 100m
 High building wall cutting 20 cm
 The transparent roof of a tall building

Precautions and details of builder mode:

1. The client (user program) does not need to know the details of the internal composition of the product, and decouples the product itself from the product creation process, so that the same creation process can create different product objects

2. Each specific builder is relatively independent and has nothing to do with other specific builders. Therefore, it is convenient to replace or add new specific builders. Users can get different product objects by using different specific builders.

3. The product creation process can be controlled more finely. The creation steps of complex products are decomposed into different methods, which makes the creation process clearer and more convenient to use programs to control the creation process.

4. Adding a new specific builder does not need to modify the code of the original class library. The commander programs for the abstract builder, which is convenient for system expansion and conforms to the "opening and closing principle".

5. The products created by the builder mode generally have more in common, and their components are similar. If there are great differences between products, the builder mode is not suitable for use, so its scope of use is limited.

6. If the internal change of the product is complex, it may lead to the need to define many specific builder classes to realize this change.

As a result, the system becomes very large, so in this case, we should consider whether to choose the builder mode.

7. Abstract factory mode VS builder mode

The abstract factory pattern realizes the creation of a product family. A product family is a series of products:

For product combinations with different classification dimensions, the abstract factory model does not need to care about the construction process, but only about what products are produced by what factory.

The builder model requires the product to be built according to the specified blueprint. Its main purpose is to produce a new product by assembling spare parts.

8. Agency mode

9. Observer mode

10. Iterator mode

11. Intermediary model

12. Status mode

13. Yuan sharing mode

14. Prototype model

15. Adapter mode

16. Bridging mode

17. Combination mode

18. Decoration mode

19. Appearance mode

20. Command mode

21. Interpreter mode

22. Memorandum model

23. Visitor model

House highHouse = houseDirector.BuilderHouse();
}
}

Operation results:

```java
 The foundation of an ordinary house is 5m
 Ordinary house wall cutting 10 cm
 Cut wall roof of ordinary house
-----------------------------------------------
The foundation of high-rise building is 100m
 High building wall cutting 20 cm
 The transparent roof of a tall building

Precautions and details of builder mode:

1. The client (user program) does not need to know the details of the internal composition of the product, and decouples the product itself from the product creation process, so that the same creation process can create different product objects

2. Each specific builder is relatively independent and has nothing to do with other specific builders. Therefore, it is convenient to replace or add new specific builders. Users can get different product objects by using different specific builders.

3. The product creation process can be controlled more finely. The creation steps of complex products are decomposed into different methods, which makes the creation process clearer and more convenient to use programs to control the creation process.

4. Adding a new specific builder does not need to modify the code of the original class library. The commander programs for the abstract builder, which is convenient for system expansion and conforms to the "opening and closing principle".

5. The products created by the builder mode generally have more in common and their components are similar. If there are great differences between products, the builder mode is not suitable for use, so its scope of use is limited.

6. If the internal changes of the product are complex, it may lead to the need to define many specific builder classes to realize this change.

As a result, the system becomes very large, so in this case, we should consider whether to choose the builder mode.

7. Abstract factory mode VS builder mode

The abstract factory pattern realizes the creation of a product family. A product family is a series of products:

For product combinations with different classification dimensions, the abstract factory model does not need to care about the construction process, but only about what products are produced by what factory.

The builder model requires the product to be built according to the specified blueprint. Its main purpose is to produce a new product by assembling spare parts.

8. Agency mode

9. Observer mode

10. Iterator mode

11. Intermediary model

12. Status mode

13. Yuan sharing mode

14. Prototype model

15. Adapter mode

16. Bridging mode

17. Combination mode

18. Decoration mode

19. Appearance mode

20. Command mode

21. Interpreter mode

22. Memorandum model

23. Visitor model

Topics: Java