The Facade Pattern

The purpose of the facade pattern is to conceal the underlying complexity of the code by using an anonymous function as an extra layer. Internal subroutines are never exposed but rather invoked through a facade which makes this pattern secure in that it never exposes anything to the developers working with it. The facade pattern is both extremely interesting and very useful for adding an extra layer of security to your already minified code. This pattern is extremely useful when coupled with the revealing module pattern.

This article is part of a series called JavaScript Design Patterns.

Advantages

Disadvantages

There aren’t any real drawbacks as it provides a unified interface to a set of interfaces in a subsystem. As a result, you aren’t forced to make any unwanted compromises, thus a win-win. One possible note worth mentioning is that a developer must decide whether the implicit cost of implementation is really worth the abstraction (though this is generally a small footprint).

Examples

1 2 3 4 5 6 7 8 9 10 11 12
// a simple facade that masks the various browser-specific methods
function addEvent( element, event, callback ) {
if( window.addEventListener ) {
element.addEventListener( event, callback, false );
} else if( document.attachEvent ) {
element.attachEvent( 'on' + event, callback );
} else {
element[ 'on' + event ] = callback;
}
}

The above is a basic example of the facade pattern.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
var MyModule = ( function( window, undefined ) {
 
// revealing module pattern ftw
function MyModule() {
function someMethod() {
alert( 'some method' );
}
function someOtherMethod() {
alert( 'some other method' );
}
// expose publicly available methods
return {
// in our normal revealing module pattern, we'd do the following:
someMethod : someMethod,
// in the facade pattern, we mask the internals so no one has direct access by doing this:
someMethod : function() {
sometMethod();
}
};
}
} )( window );

The above is a more advanced version of the facade pattern that adds security to internal methods.

Additional Resources

http://www.dofactory.com/javascript-facade-pattern.aspx
http://www.adobe.com/devnet/html5/articles/javascript-design-patterns-pt1-singleton-composite-facade.html
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#facadepatternjavascript

Other Common JS Patterns

The Module Pattern
The Revealing Module Pattern
The Singleton Pattern
The Observer Pattern
The Mediator Pattern
The Prototype Pattern
The Facade Pattern
The Factory Pattern

No comments. You could be the first!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>