introduce
In software systems, we sometimes face the creation of "a complex object", which is usually composed of sub-objects of each part using certain algorithms; due to changes in requirements, the various parts of this complex object often face drastic changes, but the algorithm that combines them together is indeed relatively stable. How to deal with this change? How to provide a "encapsulation mechanism" to isolate the changes in "each part of complex objects" so as to keep the "stable construction algorithm" in the system from changing with the needs? This is what the builder model is to be mentioned.
The 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, the user needs to specify the types to build to get them, and the specific construction process and details do not need to be known.
text
This pattern is relatively simple. Please enter the code first and then explain it
The code copy is as follows:
function getBeerById(id, callback) {
// Use ID to request data and then return the data.
asyncRequest('GET', 'beer.uri?id=' + id, function (resp) {
// callback calls response
callback(resp.responseText);
});
}
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 builder's definition, the table phase is a callback, that is, 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 the data is obtained when processing the data. The same example can also be seen in the ajax method of jquery. There are many callback functions (such as success, error callback, etc.), and the main purpose is to separate responsibilities.
Let’s also have another example of jQuery:
The code copy is as follows:
$('<div class= "foo"> bar </div>');
We only need to pass in the HTML characters to be generated, without regard to how the specific HTML object is produced.
Summarize
The builder model is mainly used to "build a complex object in steps", where "steps" is a stable algorithm, while the various parts of complex objects often change. The advantage is that the "processing process" of the builder model is exposed, which makes the builder model more flexible, and the builder model decouples the assembly process and creates specific components, so that we don't have to care about how each component is assembled.