Personal understanding of the application scenario
For example, if you want to create instances of various types of cars, there are many types of cars, but the interface definition for creating each type of car may be the same, and this mode is used.
Popular explanations of related concepts
- The definition of the interface in the example above is called Builder
- The specific implementation of the interface to each type of vehicle is called concrete Builder
- The class that is really used to create cars is called Director
The idea of realizing the pattern
1. First define the builder interface
2. Then each ConcreteBuilder class to implement this interface
3.director receives a builder instance as a parameter, and finally returns an instance of a class of cars
Sample code
function Director () {this.construct = function (builder) {builder.step1 (); BUILDER.STEP2 (); return Builder.get (); }}//because JS does not support the interface, I personally think that in fact should typescript define an interface, and then the following two classes to implement this interface function Carbuilder () {this.car = null; THIS.STEP1 = function () {This.car = new car (); }; THIS.STEP2 = function () {this.car.addParts (); }; This.get = function () {return this.car; };} function Truckbuilder () {this.truck = null; THIS.STEP1 = function () {This.truck = new truck (); }; THIS.STEP2 = function () {this.truck.addParts (); }; This.get = function () {return this.truck; };} function Car () {this.doors = 0; This.addparts = function () {this.doors = 4; }; This.say = function () {Log.add ("I am a" + this.doors + "-door car"); };} function Truck () {this.doors = 0; This.addparts = function () {this.doors = 2; }; This.say = function () {Log.add ("I am a" + this.doors + "-door truck"); };} Other developers use code snippets New Director (). Construct (new Carbuilder ());
JavaScript Design Pattern learning--builder pattern (builder mode)