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.

 
12
Kudos
 
12
Kudos

Now read this

Javascript Memory Leaks

Memory leaks are often associated with big enterprise RESTful services when an object is stored in memory but cannot be accessed by any of the running code. This causes diminishing performance ability of the application by reducing the... Continue →