Skip to main content

Facade Pattern_JavaScript Design Patterns 8

Free2015-07-26#JS#Design_Pattern#JavaScript外观模式

The Facade Pattern is very similar to the Command Pattern introduced earlier. This article details the Facade Pattern implemented in JavaScript

I. Facade Pattern

Re-encapsulating interfaces of underlying components (third-hand, fourth-hand also count as second-hand), providing more user-friendly high-level interfaces, this is the core idea of the Facade Pattern.

Facade easily brings to mind makeup, but here it's not for looking good, just for being easier to use.

II. Specific Implementation

var mod1 = {
    fun1: function() {
        // ...
    },
    fun2: function() {
        // ...
    }
    // ...
}
var mod2 = {
    fun1: function() {
        // ...
    },
    fun2: function() {
        // ...
    }
    // ...
}
// ...

// facade
var facade = {
    c: true,

    newFun1: function() {
        mod1.fun2();
        if (this.c) {
            mod1.fun1();
        }
        // ...
    },
    newFun2: function() {
        mod2.fun1();
        mod2.fun2();
        mod1.fun1();
        if (this.c) {
            mod1.fun2();
        }
        // ...
    }
    // ...
}

// invoke facade
facade.newFun1();
// invoke mods
// mod1.fun2();
// if (c) {
//     mod1.fun1();
// }
// ...

Further abstracting interfaces of lower-level modules, encapsulating simple and easy-to-use facades. Encapsulation has no end. From within modules to between modules, to between subsystems, to the system itself. As long as you're willing to continue, you can add n layers of encapsulation. You can even use the Facade Pattern to solve the problem of method names being too long, for example:

var d = {
    byId: function(strId) {
        return document.getElementById(strId);
    },
    byClass: function(strClass) {
        return document.getElementsByClassName(strClass);
    },
    byTag: function(strTag) {
        return document.getElementsByName(strTag);
    }
    // ...
}

// test
d.byId('test').innerHTML = 'test facade';

III. Pros and Cons of Facade Pattern

Pros

There's a fitting sentence in the book:

No need to focus on implementation details, and easier to use

Cons

Multiple layers of encapsulation mean long call chains, existing performance costs. If performance requirements are very high, naturally the fewer encapsulation layers the better. The closer to the bottom layer, the higher the execution efficiency. When using the Facade Pattern, you may need to consider whether re-encapsulation is worth it (whether performance costs are acceptable).

As for how much slower JQuery's $ is compared to native JS implementation, the answer is: Actually not as slow as you imagine

For more information about the Facade Pattern, please see AnYuQingYang: Design Pattern - Facade Pattern

References

  • "JavaScript Design Patterns"

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment