- Used to convert one interface to another
- an objects interface is the method and properties exposed by the object, what we use to interact with the object
- useful pattern when something changes and we don’t want to go throughout code and refactor the object
- It’s not necessary to use this pattern if the object you are changing doesn’t have a lot of dependencies
Step 1 – Page: oldInterface.js
// This will be a email validation script that will check to see if the string has an at symbol
define(function () {
'use strict';
var OldInterface = function () { }; //set up an object constructor
OldInterface.prototype.doSomethingOld = function () { //add a method to the constructor prototype
console.log('doing the old thing');
};
return new OldInterface(); //return a new instance of the object
});
Step 2 – Page: newInterface.js
// This will be a email validation script that will check to see if the string has an at symbol
define(function () {
'use strict';
var NewInterface = function () { }; //set up an object constructor
NewInterface.prototype.doSomethingNew = function (newArg) { //add a method to the constructor prototype
console.log('doing the ', newArg);
};
return new NewInterface(); //return a new instance of the object
});
Step 3 – Page: adapter.js
// This will be a email validation script that will check to see if the string has an at symbol
define(function (require) {
'use strict';
var newInterface = require('adapter/newInterface'); //require in the new interface
return {
doSomethingOld: function () { //reset the method from the oldInterface with the method from the new interface
return newInterface.doSomethingNew('new thing');
}
};
});
Step 4 – Page: init.js
define(function(require) {
'use strict';
return {
init: function() {
var OldInterfaceAdapter = require('adapter/adapter'); //set up new variable for OldInterface and rename to OldInterfaceAdapter to make it clear to any subsequent coders that we are using an adapter for the oldInterface
OldInterfaceAdapter.doSomethingOld();
}
};
});
Step 5 – Page: main.js
// JavaScript Document
require (
['adapter/init'],
function (adapter) {
'use strict';
var examples = {
adapter:adapter
};
window.runExample = function (example) {
examples[example].init();
};
}
);
Conclusion
The Adapter pattern allows us to change one part of our application without changing the others. It is also a good example of a design pattern you wouldn’t use when developing your application. Adapters are only needed when there is a change between dependencies, so this pattern only arises when issues occur.
- it is common to use design patterns when refactoring code to make things work better and more efficiently