GitHub LinkedIn RSS
Saturday, November 8, 2014

JavaScript Adapter Design Pattern


Today we'll continue the JavaScript Design Patterns series by discussing the Adapter Pattern. Adapters are added to existing code to reconcile two different interfaces. They allows programming components to work together that otherwise wouldn't because of mismatched interfaces.

Adapter may be also used to ease the use with the existing interface. If the existing code already has an interface that is doing a good job, there may be no need for an adapter. But if an interface is unintuitive or impractical for the task at hand, you can use an adapter to provide a cleaner or more option-rich interface. Let's see how it looks in the following illustration:


Here we depict the example of legacy IDataManager interface, which is deeply used within the system. With the introduction of Redis database into the system, we need an adapter to fill the gaps. Our Adapter class has to implement the getData method, to make it consistent with the system, calling in turn the scan method to iterate over data stored in the database.

The implementation will look something like this:
function RedisDataManager() {
    this.connect = function() {
        console.log('Connect to database');
    };

    this.scan = function() {
        return 'Data from database';
    };
}

function DataManager() {
    this.getData = function() {
        return 'Legacy data';
    }
}
  
function Adapter() {
    var redis = new RedisDataManager();
    redis.connect();
    
    this.getData = function() {
        return redis.scan();
    }
}

function Client(dataManager) {
    console.log(dataManager.getData());
}

var client = new Client(new Adapter());
As you can see our Client is oblivious about the IDataManager implementation, and using the Adapter Pattern, we connect the RedisDataManager to it.

Next time we'll continue our discussion about structural patterns by introducing Bridge Pattern, which is very much alike.