PS: reprint please indicate the source Author: TigerChain address: www.jianshu.com/p/300cbb9ee… This article is from TigerChain. Everyone can design patterns

Tutorial introduction

  • This tutorial is intended for beginners and will be skipped by experienced readers
  • 2, the difficulty of the tutorial is elementary, my level is limited, the content of the article will inevitably appear problems, if there are any questions welcome to point out, thank you
  • 3. Demo address: github.com/githubchen0…

The body of the

What is the Builder model

1. The Builder model in life

1. Build a house

When we build a house in life, we usually lay the foundation, build the frame “with brick or reinforced concrete”, and then paint it. That’s basically the way it is. , of course, we can do all this work, but also to find a few workers to do, of course can also can be directly to look for a designer, just say I’m going to the house, then no matter, the end ask stylist “designer for a piece of paper for workers, the workers were done” acceptance house can “as for you is I don’t care about the process of how to build, I just want results “– that’s the Builder model

2. Assemble the computer

We buy a computer is the motherboard, memory, CPU, graphics card, etc, and how to assemble it take these things to the user that is the role of the builder pattern, different people different demand for computer configuration “playing games on the graphics card” high, but the computer components are fixed, the computer we find computer city of installed personnel to pack up and this process is to build model

3. Software development

When we build a product, we need a tech lead, a product manager, a frustrated programmer. Here, the product manager is the “Director” who communicates with customers and understands product requirements, the technical Director is the abstract Builder, who lets apes do miscellaneous things, and the programmer is the manual worker, namely, the concrete Builder. Do as assigned by the tech lead “– this is a near-perfect builder model.” Why close? Because it’s not 100 percent.

2. Builder mode in the application

Definition of the builder pattern

Separating the construction of a complex object from its representation, so that the same construction process can create different representations, is the official definition. In layman’s terms, the Builder pattern is how to build an object with multiple components step by step, and the same construction process can create different products

Characteristics of the Builder pattern

Builder mode is a creation mode, which is suitable for scenarios where the process is fixed and the order is not fixed, and the target object of the build is changed “for example, draw a dog, the target is the same, but the difference is yellow dog, fat dog, thin dog, etc.”, and another scenario is to replace the multi-parameter constructor

The role of the Builder model

  • 1. Users can create complex objects without knowing the details of how objects are built.
  • 2. Users can create complex objects simply by giving them the content and type
  • 3. The builder modeller creates complex objects step by step

The builder pattern structure

role category instructions
Builder Interface or abstract class Abstract builder, not necessary
ConcreateBuilder Concrete builders Can have multiple “because each construction style may be different”
Product Ordinary class The concrete product “is the object to be built”
Director A director is also called a conductor Unified command builder to build target, director is not required

Builder pattern simple UML

2. Examples of the builder model

1. Build a computer

Xiao Ming want to assemble a desktop computer, xiao Ming don’t know anything about computer configuration, run to the computer city to directly installed the boss said I want a computer game is very cool, bother you to “configuration: ok, what do you recommend me”, so the boss let its employees “small beautiful” installed a performance according to the requirement of the xiao Ming was very cow B computer, After 1 hour the computer is installed, xiao Ming pays money to take the computer to leave. Not in a short while xiaozhang came again, want a computer that satisfies to write an article at ordinary times ok, boss is aimed at xiaozhang’s requirement to give different installed machine configuration. Different people have different configurations. “But the installation process is the same.” This is a typical builder pattern

Assemble computer simple UML

According to UML

  • 1. Create the object Computer to be built — computer.java
/** * Created by TigerChain * product class -- Created by TigerChain */
public class Computer {
    private String cpu ; // cpu
    private String hardDisk ; / / hard disk
    private String mainBoard ; / / the mainboard
    private String memory ; / / memory. Omit getter and setter}Copy the code
  • 2. Abstract Builder — Builder.java
** * Created by TigerChain */ ** * Created by TigerChain */ ** * Created by TigerChain */
public interface Builder {
    // Install the mainboard
    void createMainBoard(String mainBoard) ;
    / / install the CPU
    void createCpu(String cpu) ;
    // Install the hard disk
    void createhardDisk(String hardDisk) ;
    // Install memory
    void createMemory(String memory) ;
    // Create a computer
    Computer createComputer(a) ;
}

Copy the code
  • 3, the concrete builder, that is, the installation worker Xiao Mei — AssemblerBuilder.java
/** * Created by TigerChain */
public class AssemblerBuilder implements Builder {

    private Computer computer = new Computer() ;
    @Override
    public void createCpu(String cpu) {
        computer.setCpu(cpu);
    }

    @Override
    public void createhardDisk(String hardDisk) {
        computer.setHardDisk(hardDisk);
    }

    @Override
    public void createMainBoard(String mainBoard) {
        computer.setMainBoard(mainBoard);
    }

    @Override
    public void createMemory(String memory) {
        computer.setMemory(memory);
    }

    @Override
    public Computer createComputer(a) {
        returncomputer; }}Copy the code
  • 4, there is the boss “backseat driver” who arranges the installer’s work – Direcor.java
/** * Created by TigerChain * declares a director class "Created by TigerChain" to direct the assembly process, i.e. the process by which a computer is Created */
public class Director {
    private Builder builder ;
	// Use multistate, the machine is very many, I care you xiao Mei, Xiao LAN, piggy, I accept all
    public Direcror(Builder builder){
        this.builder = builder ;
    }
	At the end of the day, the boss just wants to see the finished product -- delivered to the customer
    public Computer createComputer(String cpu,String hardDisk,String mainBoard,String memory){
        // The specific work is done by the installation workers
        this.builder.createMainBoard(mainBoard);
        this.builder.createCpu(cpu) ;
        this.builder.createMemory(memory);
        this.builder.createhardDisk(hardDisk);
        return this.builder.createComputer() ; }}Copy the code
  • 5. Test classes
/** * Created by TigerChain test class */
public class Test {
  public static void main(String args[]){
	  // Loader Xiao Mei
      Builder builder = new AssemblerBuilder() ;
      // The boss transferred Xiao Ming's needs to Xiao Mei
      Direcror direcror = new Direcror(builder) ;
      // The boss finally got the finished machine and Mei did all the work
      Computer computer = direcror.createComputer("Intel Core I9 7900X"."Samsung M9T 2TB (HN-M201RAD)"."AORUS Z270X-Gaming 7".Cras II red light 16GB DDR4 3000); System.out.println("Xiaoming this computer uses: \n"+computer.getMainBoard()+"The mainboard \ n"+computer.getCpu()+" CPU\n"+computer.getHardDisk()+"Hard disk \ n"+computer.getMainBoard()+"Memory \ n"); }}Copy the code
  • 6. Run and view the result

How, as to small piece, piglet should install machine the configuration that wants oneself to give boss can, next boss how install machine need not you tube, you wait to collect good machine child

2. Build a house

The basic steps and process of building a house are fixed: laying the foundation, laying the frame, and then pouring. “Whether to build a bungalow or a building is the specific needs of each client.” Generally speaking, houses are built in three ways:

  • “There is no way some people are cattle B, their own design, their own hands, of course, this belongs to the small house, you let a person to build a 32 layer let me see”
  • 2. The man who wanted to build a house was a contractor who found a group of workers and did it himself
  • 3, people who want to build a house is an ordinary person, what also can’t, looking for a designer says “I’m going to build a house, a north-south all-transparent, evergreen four show”, stylist says there is no problem, stylist threw the designed drawings to contractor said: “like this” guy, contractor with drawings to give the workers division of labor subcontracting, finally completed

Build house Builder Pattern simple UML

According to UML

  • 1, House object house.java
/** * Created by TigerChain * final product -- house */
public class House {
    / / play ground
    private String foundation ;
    / / framework
    private String frame ;
    / / casting
    privateString pouring ; . Omit setter and getter}Copy the code
  • 2, abstract builder “houseBuilder.java”
public interface HouseBuilder {
    / / play ground
    void doFoundation(a) ;
    / / framework
    void doFrame(a) ;
    / / water
    void dpPouring(a) ;
    // The house was completed
    House getHouse(a) ;
}
Copy the code
  • pingfangBuilder.java
/** * Created by TigerChain */
public class PingFangBuilder implements HouseBuilder {

    private House house = new House() ;

    @Override
    public void doFoundation(a) {
        house.setFoundation("A foundation for a bungalow.");
    }

    @Override
    public void doFrame(a) {
        house.setFrame("A framework for building a bungalow.");
    }

    @Override
    public void dpPouring(a) {
        house.setPouring("You don't need to water a bungalow. You can just brush it by hand.");
    }

    @Override
    public House getHouse(a) {
        returnhouse; }}Copy the code
  • 4, specific builder “workers” — building building LoufangBuilding.java
/** * Created by TigerChain */
public class LouFangBuilder implements HouseBuilder {

    private House house = new House() ;
    @Override
    public void doFoundation(a) {
        house.setFoundation("Lay the foundation of the building ten meters deep.");
    }

    @Override
    public void doFrame(a) {
        house.setFrame("The building must be framed with very strong reinforced concrete.");
    }

    @Override
    public void dpPouring(a) {
        house.setPouring("Just take a tank truck and fill the frame with concrete.");
    }

    @Override
    public House getHouse(a) {
        returnhouse; }}Copy the code
  • 5. HouseDirector: Java
/** * Created by TigerChain */
public class HouseDirector {
    // Command the contractor
    public void buildHouse(HouseBuilder houseBuilder){ houseBuilder.doFoundation(); houseBuilder.doFrame(); houseBuilder.dpPouring(); }}Copy the code
  • 6. Test test.java
/** * Created by TigerChain */
public class Test {
    public static void main(String args[]){

        // First, the client builds the house by himself
        System.out.println("======== Clients build their own houses and must know the details of the building ========");
        House house = new House() ;
        house.setFoundation("Build your own house: Lay the foundation.");
        house.setFrame("Users build their own houses: Build frames");
        house.setPouring("User-built houses: Pouring");

        System.out.println(house.getFoundation());
        System.out.println(house.getFrame());
        System.out.println(house.getPouring());


        // Way 2, the client to find a builder to build a house "to act as the contractor role", but to know how to build the house "call the builder to build the house order"
        System.out.println("======== the customer directly calls the worker "builder" who builds the house. The customer calls the builder method to build the house. The customer must know how the house is built ========.");

        HouseBuilder houseBuilder = new PingFangBuilder() ;
        houseBuilder.doFoundation();
        houseBuilder.doFrame();
        houseBuilder.dpPouring();
        House house1 = houseBuilder.getHouse() ;
        System.out.println(house1.getFoundation());
        System.out.println(house1.getFrame());
        System.out.println(house1.getPouring());

        // Use the builder mode, find a designer, "the designer takes a group of builders to work", tell him what kind of house I want, and finally the client only asks the designer for the house
        System.out.println("======== The client directly finds a designer, and the designer directs the builder to build a house. The house is miscellaneous, and the client doesn't care about it. Finally, he just asks the designer for the house.);

        HouseBuilder pingFangBuilder = new PingFangBuilder() ;
        HouseDirector houseDirector = newHouseDirector() ; houseDirector.buildHouse(pingFangBuilder); House houseCreateByBuilder = pingFangBuilder.getHouse() ; System.out.println(houseCreateByBuilder.getFoundation()); System.out.println(houseCreateByBuilder.getFrame()); System.out.println(houseCreateByBuilder.getPouring()); }}Copy the code

We compared three ways: build a house by yourself, hire a worker to build a house, and hire a designer to build a house to gradually feel the advantages of the builder model

  • 6. Run and view the result

We can see that the last one is the most comfortable. When building a house, we can directly outsource it to the designer, and we don’t need to worry about it. Then we can ask the designer to build a finished house.

3. The builder pattern replaces the multi-parameter constructor, using the assembling computer as an example

Earlier we said that Director is not necessary in the builder mode, the Director’s role is not to construct the product, “build the product is the builder’s job,” but to direct and coordinate the construction steps. “When there is a new builder, the abstract builder is implemented directly, regardless of the specific execution steps. That’s what directors do. “Let’s go straight to the code

  • 1. Original Computer.java
public class Computer {
    private String mainBoard ;     / / the mainboard
    private String cpu ;           // cpu
    private String hd ;            / / hard disk
    private String powerSupplier ; / / power
    private String graphicsCard;   / / graphics card

    // Other optional configurations
    private String mouse ; / / mouse
    private String computerCase ; / / case
    private String mousePad ;   / / mouse pad
    private String other ;  // Other accessories


    public Computer(String mainBoard,String cpu,String hd,String powerSupplier, String graphicsCard,String mouse,String computerCase,String mousePad,String other){
        this.mainBoard = mainBoard ;
        this.cpu = cpu ;
        this.hd = hd ;
        this.powerSupplier = powerSupplier ;
        this.graphicsCard = graphicsCard ;
        this.mouse = mouse ;
        this.computerCase = computerCase ;
        this.mousePad = mousePad ;
        this.other = other ;
    }

    public Computer(String mainBoard,String cpu,String hd,String powerSupplier, String graphicsCard,String mouse,String computerCase,String mousePad){
        this.mainBoard = mainBoard ;
        this.cpu = cpu ;
        this.hd = hd ;
        this.powerSupplier = powerSupplier ;
        this.graphicsCard = graphicsCard ;
        this.mouse = mouse ;
        this.computerCase = computerCase ;
        this.mousePad = mousePad ; }... Omit other constructors and setter and getter methods}Copy the code

If we want to call this class will have to pass in the constitutive parameters method “countless parameters” “if there are some options, we have to rewrite the constructor”, or are called multiple setter method, can give an object assignment, the method is feasible, but also too bullshit! “” who can remember those parameters, Then the builder pattern can solve the multi-parameter construction method to build objects

  • 2. Build Computerb. Java with the builder
/** * Created by TigerChain * instead of multi-parameter constructors -- constructor pattern */
public class ComputerB {

    private String mainBoard ;     / / the mainboard
    private String cpu ;           // cpu
    private String hd ;            / / hard disk
    private String powerSupplier ; / / power
    private String graphicsCard;   / / graphics card

    // Other optional configurations
    private String mouse ; / / mouse
    private String computerCase ; / / case
    private String mousePad ;   / / mouse pad
    private String other ;  // Other accessories

	// ComputerB acts as the Director itself
    private ComputerB(ComputerBuilder builder) {
        this.mainBoard = builder.mainBoard ;
        this.cpu = builder.cpu ;
        this.hd = builder.hd ;
        this.powerSupplier = builder.powerSupplier ;
        this.graphicsCard = builder.graphicsCard ;

        this.mouse = builder.mouse ;
        this.computerCase = builder.computerCase ;
        this.mousePad = builder.mousePad ;
        this.other = builder.other ;
    }
	// Declare a static memory class Builder
    public static class ComputerBuilder{
        // A computer must be configured
        private String mainBoard ;     / / the mainboard
        private String cpu ;           // cpu
        private String hd ;            / / hard disk
        private String powerSupplier ; / / power
        private String graphicsCard;   / / graphics card

        // Other optional configurations
        private String mouse ; / / mouse
        private String computerCase ; / / case
        private String mousePad ;   / / mouse pad
        private String other ;  // Other accessories

		// Specify that these parameters must be passed. This is just an example. The possible parameters are optional.
        public ComputerBuilder(String mainBoard,String cpu,String hd,String powerSupplier,String graphicsCard){
            this.mainBoard = mainBoard ;
            this.cpu = cpu ;
            this.hd = hd ;
            this.powerSupplier = powerSupplier ;
            this.graphicsCard = graphicsCard ;
        }

        public ComputerBuilder setMainBoard(String mainBoard) {
            this.mainBoard = mainBoard;
            return this ;
        }

        public ComputerBuilder setCpu(String cpu) {
            this.cpu = cpu;
            return this; }... Some other setXXX() methods// Build the final product
        public ComputerB build(a){
            return new ComputerB(this); }}}Copy the code

The code comments are so detailed that at first glance they seem to have nothing to do with the Builder pattern, but if we take a closer look at this, it is a builder pattern. Let’s take a look: The product is –>ComputerB, the concrete builder is a static memory class –>ComputerBuilder, but there is no abstract builder and director. So this is a typical builder model

  • 3, How to call a Test class test.java
public class Test {
    public static void main(String args[]){

        // Do not use builder mode
        Computer computer = new Computer("Main board"."cpu"."hd"."Power"."Graphics"
        ,"Mouse"."The case"."Mouse pad"); System.out.println("Assemble a computer using a common construction method:"+computer.toString());

        // Use builder mode
        ComputerB computerB = new ComputerB.ComputerBuilder("Main board"."cpu"."hd"."Power"."Graphics")
                .setMouse("Mouse").setMousePad("Mat").build() ;
        System.out.println("Build a computer using Builder mode:"+computerB.toString()); }}Copy the code

We built the computer using the normal construct “caller can spit blood” and the builder model, Can see the builder pattern call new ComputerB.Com puterBuilder (XXX). Setxxx (). The setxxx (). The build () method is called dot directly call “also known as streaming call, so call more convenient, to the point that”, If you have used RX, it will feel very good

  • 4, run to see the results

If you don’t want to use the builder pattern in the future if you encounter multi-parameter constructs

Android source code in the builder mode

1, the AlertDialog

AlertDialog is a popover component that allows you to add lists, radio lists, text boxes, multiple selection lists, etc. Inside, it uses the typical builder mode. Let’s take a look at the basic use of AlertDialog

// Create a builder
   AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Use the builder pattern instead of the multi-parameter constructor
   Dialog dialog= builder.setTitle(XXX).setIcon(XXX).setXXX(xxx).create() ;
   dialog.show() ;
Copy the code

AlertDialog simple UML

AlertDialog core code stripping

The figure above clearly shows the Builder mode of AlertDialog. “AlertDialog.Builder acts as Builder, ConcreateBuilder, Director, etc.”

2. Notification’s setLatestEventInfo method is “outdated, but ideas can be learned”

If we look at setLatestEventInfo for Notification, we can see that the builder mode is being used

The above method is replaced by “setLatestEventInfo also calls notification. Builder”. The real Builder mode is notification. Builder

If you want to support to low version can use android. The support. The v4. App. NotificationCompat. Builder to create the Notification name a look is a Builder pattern, Interested can look at NotificationCompat. The Builder of the source code

3, AnimatorSet. Builder

AnimatorSet is used to execute a collection of animations in a selected order. We can use AnimatorSet.Builder to add the order in which the animations are played.

Usage Examples

AnimatorSet animSet = new AnimatorSet();  
//AnimatorSet.Builder cannot be created directly, can only be created by play(Animation)
AnimatorSet.Builder builder = animSet.play(anim2);  
builder.with(anim3).after(anim1).before(anim4);Anim1, anim2, anim3, anim4
animSet.setDuration(200);  
animSet.start();  
Copy the code

The core code

The advantages and disadvantages of the builder model

advantages

  • 1. Make the steps of creating a product “make the steps of creating a product clearer and more intuitive in a different way” separate from the product itself, that is, create different products using the same creation process
  • 2. Each builder is independent of each other, thus achieving decoupling, so if you want to replace an existing builder, it is very convenient to add an implementation.

disadvantages

  • 1, only applicable to products with the same characteristics of the “process and steps”, if the difference between products is very large, it does not apply to the “limited scope of use”
  • 2. In case the product changes internally that day, multiple builders will have to modify it, which will cost too much

5. Usage scenarios of builder mode

  • 1. If an object has a very complex internal structure, “these products usually have a lot of attributes,” then use the Builder pattern
  • 2. If you want to separate the creation and use of complex objects, use the Builder pattern to create different products using the same creation steps.

6. Builder vs. Simple Factory

The similarities

They’re all in the creative pattern, they’re all creating products.

The difference between

  • 1. Different granularity of object creation

The factory model creates objects that look like birds, while the Builder model creates a composite product made up of complex parts that make up different products

  • 2. Different concerns:

Factory mode focuses on “not caring about the components of the product” as long as the object is created, whereas builder mode does not seem to create the product, but knows the components of the product

That’s it, we’re done with the Builder mode, be sure to give it a try, follow bloggers for more exciting articles waiting for you, and reach out your little hands and give it a thumbs up

Public account: TigerChain welcomes your attention