In depth understanding of JavaScript series (27) : builder's schema for design patterns

  • 2020-05-10 17:41:53
  • OfStack

introduce

In a software system, sometimes it is faced with the creation of "1 complex object", which is usually composed of the sub-objects of each part with 1 definite algorithm. The various parts of this complex object often face drastic changes due to changing requirements, but the algorithm that combines them in 1 is relatively stable. How to deal with this change? How to provide a "encapsulation mechanism" to isolate changes in "parts of complex objects" so as to keep the "stable build algorithm" in the system from changing with requirements? That's the builder model.

The builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations. That is, if we use the builder pattern, then the user needs to specify the types to build and get them, without having to know the process and details of building them.

The body of the

This pattern is relatively simple, code first, then explain


function getBeerById(id, callback) {
    // use ID To request the data and then return the 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 definition of the builder, the callback is, after get the data that is to say how to display and handle depends on the callback function, accordingly the callback function does not need to pay attention to when processing data is how to obtain data, and the same example can be seen in jquery ajax method, there are a lot of the callback function (such as success error callback, etc.), the main purpose is the separation of duties.

Another example of jQuery:


$('<div class= "foo"> bar </div>');

We only need to pass in the HTML character to be generated, not the relationship to how the concrete HTML object was produced.

conclusion

Builders mode is mainly used for building a complex object "step", in which "step" is a stable algorithm, and each part of a complex object is often change, its advantage is: the builder pattern of "process" is exposed, which makes the builder pattern more flexible, and builders mode decoupling the assembly process and to create specific components, make we don't need to care about how each part is assembled.


Related articles: