SoFunction
Updated on 2025-03-02

Detailed explanation of how to use the builder mode of JS design pattern

Detailed explanation of how to use the builder mode of JS design pattern

Updated: August 30, 2023 09:42:20 Author: Mu Zhongqing
JS Builder Pattern is a creative design pattern. It can be used to create complex objects, separate the construction steps and representations of objects, so that different objects can be flexibly constructed. This article will introduce the usage of JS Builder Pattern in detail through code examples. Friends who need it can refer to it.

definition

A creative design pattern that can be used to create complex objects, andConstruction steps and representation separation, so that different objects can be built flexibly.

Participants

  • Product: Complex objects that need to be constructed.
  • Abstract Builder: Defines an abstract interface for creating various parts of the product object. It usually contains a method (usually called build) for obtaining the final product.
  • Concrete Builder: The abstract builder interface is realized and responsible for the specific product construction process. It defines a series of build steps and provides methods to obtain the final built product.
  • Director: Responsible for controlling the construction processSequence and process. It builds the product by calling the specific builder's methods.

advantage

  • Separate the construction process and representation, making the construction process reusable and easy toExpand and modify
  • CanRefine constructionEach step in the process allows you to flexibly control the construction of objects.
  • Hidden construction of complex objectsdetail, simplifies client code.

Applicable scenarios

  • When the object construction process hasMultiple steps, and each step can have a different implementation method.
  • When it is necessary to build objects with different representations or configurations, by adjusting the implementation of the specific builder, you canCreate different product variants
  • whenThe main business logic of the construction process independent of the objectallows for more flexibility in building objects.

Example

// Product category: Computerclass Computer {
  private processor: string;
  private memory: number;
  private storage: number;
  constructor(
    public processor: string,
    public memory: number,
    public storage: number
  ) {}
  public getSpecs(): void {
    (
      `Processor: ${} | Memory: ${}GB | Storage: ${}GB`
    );
  }
}
// Abstract Builder Interfaceinterface ComputerBuilder {
  setProcessor(processor: string): void;
  setMemory(memory: number): void;
  setStorage(storage: number): void;
  build(): Computer;
}
// Specific builder Aclass GamingComputerBuilder implements ComputerBuilder {
  private computer: Computer;
  constructor() {
    // The default configuration of computer products is: Intel i7, 16G memory, 512G hard disk     = new Computer("Intel i7", 16, 512);
  }
  // Build processor type  setProcessor(processor: string): void {
     = new Computer(
      processor,
      ,
      
    );
  }
  // Build memory size  setMemory(memory: number): void {
     = new Computer(
      ,
      memory,
      
    );
  }
  // Build hard disk size  setStorage(storage: number): void {
     = new Computer(
      ,
      ,
      storage
    );
  }
  // A method for obtaining the final product  build(): Computer {
    return ;
  }
}
// Specific builder Bclass OfficeComputerBuilder implements ComputerBuilder {
  private computer: Computer;
  constructor() {
     = new Computer("Intel i5", 8, 256);
  }
  setProcessor(processor: string): void {
     = new Computer(
      processor,
      ,
      
    );
  }
  setMemory(memory: number): void {
     = new Computer(
      ,
      memory,
      
    );
  }
  setStorage(storage: number): void {
     = new Computer(
      ,
      ,
      storage
    );
  }
  build(): Computer {
    return ;
  }
}
// Commanderclass ComputerDirector {
  private builder: ComputerBuilder;
  constructor(builder: ComputerBuilder) {
     = builder;
  }
  constructComputer(): Computer {
    ("Intel i7");
    (16);
    (512);
    return ();
  }
}
// Client codeconst gamingBuilder: ComputerBuilder = new GamingComputerBuilder();
const officeBuilder: ComputerBuilder = new OfficeComputerBuilder();
const gamingDirector: ComputerDirector = new ComputerDirector(gamingBuilder);
const gamingComputer: Computer = ();
(); // Output: Processor: Intel i7, Memory: 16GB, Storage: 512GBconst officeDirector: ComputerDirector = new ComputerDirector(officeBuilder);
const officeComputer: Computer = ();
(); // Output:Processor: Intel i5, Memory: 8GB, Storage: 256GB

Application scenarios:

  • Construction of XMLHttpRequest (XHR) object:
    • XHR is an object provided by the browser for making Ajax requests.
    • Using the Builder Design Pattern, different types of XHR objects can be built by setting different properties and methods.
const xhr = new XMLHttpRequest();
("GET", "/data"); // Build url and method("Content-Type", "application/json"); // Build request header = function () {
  // Build callbacks  if ( ===  &&  === 200) {
    ();
  }
};
(); // Build the request body
  • DOM element creation:
    • In JavaScript, we can use()Method to create DOM elements.
    • Using the Builder Design Pattern, you can set the attributes, styles, and child elements of an element in a specific order and then add them to the document.
// Not a strict builder design patternconst div = ("div"); // Note that the interpreter design pattern is also used here("container");
("width", "300px");
("height", "200px");
const heading = ("h1");
(heading);
(div);

This is the article about the detailed explanation of how to use the JS design pattern. This is the end of this article. For more related content on JS builder pattern, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • JS
  • Builder Mode

Related Articles

  • JavaScript implements simple plane war game

    This article mainly introduces the simple aircraft war game for you in detail. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2022-05-05
  • How to use let and const in the ES6 introductory tutorial

    This article mainly introduces you to the use of let and const introductory tutorials for ES6. The example code is introduced in this article in detail, which has a certain reference learning value for everyone to learn or use ES6. If you need it, let’s learn together.
    2019-04-04
  • Vue formData implements image upload

    This article mainly introduces the implementation of Vue formData to upload images in detail. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2019-08-08
  • Javascript Memoization cache function usage instructions

    Memoization is a method to cache the return value of a function. Friends who learn js object-oriented can refer to it.
    2010-05-05
  • JS defines carriage return event (implementation code)

    The implementation code for defining the carriage return event based on JS. Friends who need it can refer to it
    2013-07-07
  • JavaScript agrees to wait for code implementation experience

    JavaScript function description: This program disables the consent button for ten seconds on the page of the consent agreement, and displays the countdown on the button's value.
    2011-01-01
  • Introduction to loading examples using n window onloads at the same time

    Load multiple window onloads to use them at the same time. I believe many people have not used them. Next, let me introduce the specific usage methods in detail. Interested friends can refer to them.
    2013-04-04
  • Read Notes (I) False Value and === operator

    JavaScript false values ​​and === operators, friends who are learning js can take a look.
    2010-11-11
  • Simple implementation code for custom scrollbar effect of JS

    This article mainly introduces the simple implementation code of JS custom scrollbar effect in detail. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2017-07-07
  • How to deal with javascript showing last week and last month dates

    This article mainly shares with you the processing methods of JavaScript implementation last week and last month. It has certain reference value. Interested friends can refer to it.
    2016-02-02

Latest Comments