In depth understanding of JavaScript series (30) : detailed explanation of appearance patterns of design patterns

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

introduce

The appearance pattern (Facade) provides a one-in-one interface for a set of interfaces in a subsystem. This module defines a high-level interface that is more usable for the subsystem.

The body of the

The appearance pattern not only simplifies the interface in the class, but also decouples the interface from the caller. The look-and-feel pattern, often seen as a must-have for developers, encapsulates complex operations and creates a simple interface to invoke.

The facade pattern is often used in the JavaScript library to encapsulate interfaces that are compatible with multiple browsers. The facade pattern allows us to call the subsystem indirectly, thus avoiding unnecessary errors due to direct access to the subsystem.

The appearance pattern has the advantage of being easy to use and lightweight in its own right. However, there are also disadvantages to the appearance pattern, which can cause performance problems when used continuously by developers, because the availability of the functionality is checked every time it is invoked.

Here is an unoptimized piece of code that USES the appearance pattern to create a cross-browser usage method by detecting browser features.


var addMyEvent = function (el, ev, fn) {
    if (el.addEventListener) {
        el.addEventListener(ev, fn, false);
    } else if (el.attachEvent) {
        el.attachEvent('on' + ev, fn);
    } else {
        el['on' + ev] = fn;
    }
};

Another simple example is to use an interface to encapsulate other interfaces:

var mobileEvent = {
    // ...
    stop: function (e) {
        e.preventDefault();
        e.stopPropagation();
    }
    // ...
};

conclusion

So when do you use appearance patterns? 1 generally speaking, there are three stages:

First of all, at the beginning of the design, it should be consciously separated from the two different layers, such as the classic 3-layer structure, and the appearance Facade should be built between the data access layer and the business logic layer, and between the business logic layer and the presentation layer.

Second, in the development phase, subsystems tend to become more and more complex due to constant refactoring and evolution. Adding the appearance of Facade can provide a simple interface to reduce their dependence on each other.

3, in the maintenance of a large legacy systems, this system may have been difficult to maintain, this time using Facade appearance is also very appropriate, for 1 appearance Facade class system development, to provide design rough and highly complex legacy code more clear interface, make the new system and Facade object interaction, Facade interact with legacy code all the complex work.

Reference: big talk design mode


Related articles: