Last active
December 17, 2015 06:49
-
-
Save timkg/5568259 to your computer and use it in GitHub Desktop.
A simple implementation of Interfaces in Javascript. Allows you to define Interfaces with a bunch of methods. Defines Function.prototype.implement to be called on constructor functions which want to implement an interface. Throws errors if not all interface methods were declared.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Interface(methodNames) { | |
var self = this; | |
methodNames.forEach(function(name) { | |
self[name] = function() { | |
throw new Error('Interface methods should not be called directly. Overwrite with specific implementation details.'); | |
}; | |
}); | |
} | |
Function.prototype.implement = function(_interface, methodHash) { | |
var proto = this.prototype = {}; | |
for (var prop in methodHash) { | |
if (typeof methodHash[prop] === 'function') { | |
proto[prop] = methodHash[prop]; | |
} | |
} | |
for (var prop in _interface) { | |
if (typeof _interface[prop] === 'function') { | |
try { | |
proto[prop](); | |
} catch (e) { | |
throw new Error('Did not declare Interface method named ' + prop + '. Go back and declare this method.'); | |
} | |
} | |
} | |
} | |
var UserRepo = new Interface(['get', 'save', 'edit', 'getAll']); | |
function UserRepoRedis() { | |
// implementation-sepcific details | |
} | |
UserRepoRedis.implement(UserRepo, { | |
get: function() {} | |
, save: function() {} | |
, edit: function() {} | |
, getAll: function() {} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment