Introduced
In the software system, sometimes faced with the creation of "a complex object", it is usually composed of the child objects of each part by a certain algorithm; Because of the change of requirements, the various parts of this complex object often face drastic changes, but the algorithms that combine them are relatively stable. How to deal with this change? How to provide a "encapsulation mechanism" to isolate the "various parts of complex objects" changes, so as to maintain the system of "stable construction algorithm" does not change as the requirements change? This is the builder model to say.
The builder pattern separates the construction of a complex object from its representation, allowing the same build process to create different representations. That is to say, if we use the builder model, then the user needs to specify the type that needs to be built to get them, and the process and details of the construction need not be known.
Body
This pattern is relatively simple, first on the code, and then explain
Copy Code code as follows:
function Getbeerbyid (ID, callback) {
Use IDs to request data, and then return data.
Asyncrequest (' Get ', ' beer.uri?id= ' + ID, function (RESP) {
Callback Call 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 is a callback, that is, how to display and process the data later depends on the callback function, the corresponding callback function does not need to focus on how to obtain the data when processing the data, the same example can be seen in the jquery Ajax method, There are a lot of callback functions (such as success, error callback, etc.), the main purpose is separation of duties.
Again one example of jquery:
Copy Code code as follows:
$ (' <div class= ' foo ' > Bar </div> ');
We just need to pass in the HTML characters we want to generate without having to relate how the specific HTML object is produced.
Summarize
The builder model is primarily used to "step through a complex object" in this one "step" is a stable algorithm, and the various parts of complex objects are often changed, the advantage is that the builder model of "processing technology" is exposed, so that the builder model more flexible, and the builder model decoupled the assembly process and created the concrete parts so that we didn't have to care about how each part was assembled.