Design mode-06 builder mode

Posted by 8mycsh on Fri, 11 Feb 2022 04:21:51 +0100

Basic introduction

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

  • It separates the construction of components (in the charge of Builder) and assembly (in the charge of Director), so that complex objects can be constructed. This pattern is applicable to the complex construction process of an object

  • Due to the decoupling of construction and assembly. Different builders and the same assembly can also make different objects; With the same builder, different assembly sequences can also make different objects to achieve better reuse.

  • The builder pattern can separate the component from its assembly process and create a complex object step by step. Users only need to specify the type of complex object to get the object without knowing the specific construction details inside

The Builder pattern includes the following roles:

  • Abstract builder class: this interface defines which parts of a complex object should be created, and does not involve the creation of specific component objects

  • Concretebuilder: implement the Builder interface, complete the specific creation method of each component of complex products, and provide product examples after the construction process is completed.

  • Product: complex object to create

  • Director: call the specific builder to create each part of the complex object. The director does not involve the information of the specific product, but is only responsible for ensuring that each part of the object is created completely or in a certain order

Mode advantages:

  • In terms of the overall change of encapsulation mode, the encapsulation mode builder can achieve good stability

  • In the builder mode, the client 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

  • It can more finely control the product creation process, decompose the creation steps of complex products into different methods, and make it easier to use programs to control the creation process

  • The builder mode is easy to expand. If there are new requirements, it can be completed by implementing a new builder class. Basically, there is no need to modify the code that has passed the test before. Therefore, it will not introduce risks to the original functions and comply with the opening and closing principle

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

Application scenario:

  • The created object is complex and consists of multiple components. Each component is facing complex changes, but the construction sequence between components is stable

  • The algorithm of creating a complex object is independent of the components of the object and the assembly method, that is, the construction process and final representation of the product are independent

code implementation

The production of bicycle is a complex process, which includes the production of frame, seat and other components. The frame has a variety of materials, and the seat has a variety of materials. For the production of bicycles, the builder mode can be used

  • Bicycles:

    public class Bike {   
        private String frame;    
        private String seat;    
        // ...
    }

  • Abstract builder class:

    public abstract class Builder {
        protected Bike bike = new Bike();
    ​
        public abstract void buildFrame();
        public abstract void buildSeat();
        public abstract Bike createBike();
    }

  • Specific builder class:

    //Moby bike Builder class
    public class MobikeBuilder extends Builder {
        @Override
        public void buildFrame() {
            bike.setFrame("Aluminum alloy frame");
        }
        @Override
        public void buildSeat() {
            bike.setSeat("Leather seat");
        }
        @Override
        public Bike createBike() {
            return bike;
        }
    }
    //ofo Builder class
    public class OfoBuilder extends Builder {
        @Override
        public void buildFrame() {
            bike.setFrame("Carbon fiber frame");
        }
        @Override
        public void buildSeat() {
            bike.setSeat("Rubber seat");
        }
        @Override
        public Bike createBike() {
            return bike;
        }
    }

  • Commander category:

    public class Director {
        private Builder builder;
    ​
        public Director(Builder builder) {
            this.builder = builder;
        }
    ​
        public Bike construct() {
            builder.buildFrame();
            builder.buildSeat();
            return builder.createBike();
        }
    }

  • Test class:

    public static void main(String[] args) {
        Director director = new Director(new MobileBuilder());
        // The conductor directed the assembly of bicycles
        Bike bike = director.construct();
        System.out.println(bike.getFrame() + bike.getSeat());
    }

Mode expansion

When a class constructor needs to pass in many parameters, if you create an instance of this class, the code readability will be very poor, and it is easy to introduce errors. At this time, you can use the builder pattern for reconstruction

  • Code before Refactoring:

    public class Phone {
        private String cpu;
        private String screen;
        private String memory;
        private String mainboard;
    }
    public static void main(String[] args) {
        //Building Phone objects
        Phone phone = new Phone("intel","Samsung screen","Kingston","ASUS");
        System.out.println(phone);
    }

  • Refactored Code:

    public class Phone {
        private String cpu;
        private String screen;
        private String memory;
        private String mainboard;
    ​
        private Phone(Builder builder) {
            cpu = builder.cpu;
            screen = builder.screen;
            memory = builder.memory;
            mainboard = builder.mainboard;
        }
    ​
        public static final class Builder {
            private String cpu;
            private String screen;
            private String memory;
            private String mainboard;
    ​
            public Builder() {}
            //The return value is this, so chain programming is supported
            public Builder cpu(String val) {
                cpu = val;
                return this;
            }
            public Builder screen(String val) {
                screen = val;
                return this;
            }
            public Builder memory(String val) {
                memory = val;
                return this;
            }
            public Builder mainboard(String val) {
                mainboard = val;
                return this;
            }
            public Phone build() {
                return new Phone(this);
            }
        }
    }
    ​
    public static void main(String[] args) {
        Phone phone = new Phone.Builder()
            .cpu("intel")
            .mainboard("ASUS")
            .memory("Kingston")
            .screen("Samsung")
            .build();
        System.out.println(phone);
    }

Mode comparison

Factory method mode vs. builder mode

  • The factory method pattern focuses on the creation of the overall object

  • The builder pattern focuses on the process of component construction, which is intended to create a complex object through precise construction step by step

Abstract factory mode vs. builder mode

  • Abstract factory mode realizes the creation of product family. A product family is such a series of products. It does not need to care about the construction process, but only about what products are produced by what factory

  • The builder mode requires the product to be built according to the specified blueprint, and the main purpose is to produce a new product by assembling spare parts

    If the abstract factory pattern is regarded as an auto parts production factory to produce the products of a product family, the builder pattern is an auto assembly factory, which can return a complete car through the assembly of parts

Topics: Design Pattern