Home > Article > Web Front-end > In-depth understanding of JavaScript series (27): Detailed explanation of the builder pattern of design patterns_javascript skills
Introduction
In software systems, sometimes we are faced with the creation of "a complex object", which is usually composed of sub-objects of each part using a certain algorithm; due to changes in requirements, each part of this complex object often faces drastic changes. changes, but the algorithm that combines them is relatively stable. How to deal with this change? How to provide an "encapsulation mechanism" to isolate changes in "various parts of complex objects" so as to keep the "stable construction algorithm" in the system from changing as requirements change? This is what is called the Builder Pattern.
Builder pattern can separate the construction of a complex object from its representation, so that the same construction process can create different representations. That is to say, if we use the builder mode, then the user needs to specify the types to be built to get them, and the specific construction process and details do not need to be known.
Text
This mode is relatively simple. Code it first and then explain it
var el = document.querySelector('#test');
el.addEventListener('click', getBeerByIdBridge, false);
function getBeerByIdBridge(e) {
GetBeerById(this.id, function (beer) {
console.log('Requested Beer: ' beer);
});
}
According to the definition of the builder, appearance is a callback, which means that how to display and process the data after obtaining it depends on the callback function. Correspondingly, the callback function does not need to pay attention to how to obtain the data when processing the data. Same example You can also see in jquery's ajax method that there are many callback functions (such as success, error callbacks, etc.), and the main purpose is separation of responsibilities.
Similarly another jQuery example:
Summary
The builder pattern is mainly used to "build a complex object step by step", in which "step by step" is a stable algorithm, while the various parts of the complex object change frequently. Its advantages are: The "processing technology" is exposed, which makes the builder mode more flexible, and the builder mode decouples the assembly process and the creation of specific parts, so that we do not have to care about how each part is assembled.