Adapter Pattern in JavaScript

The adapter pattern is a concept where two incompatible interfaces are made to work together using the adapter. The adapter is useful for when changing frameworks in large complex projects. Say you started development using Backbone however after management makes an executive decision your team now has to align to the company’s standards which might be Dojo or Ember. This requires massive code change to switch all the Backbone code into Ember. This obviously is not a smart decision so using an adapter, while painful to do, is still better than the former option.

To implement an adapter interface we simply need to return a function or a set of functions that changes the current interface when consumed.

var AjaxLoggerAdapter = {
    log: function(arg) {
        AjaxLogger.sendLog(arg);
    }
};

/* Adjust the LoggerFactory */
var LoggerFactory = {
    getLogger: function() {
        // just gotta change what's returned here
        return AjaxLoggerAdapter;
    },
    ...
};

Source

Here the method for getLogger is overwritten to adapt the AjaxLoggerAdapter so that it uses the sendLog method of the object AjaxLogger. This allows us to externalize a function of an object to consume other implementations.

 
13
Kudos
 
13
Kudos

Now read this

ES7 Async Await in JavaScript

This is a blog post on the async and await functionality coming to JavaScript. It is currently on Stage 3 Draft but is well adopted in tools such as Babel which transpiles the code into Generators (which is actually transpiled again by... Continue →