// 接口 var Interface = function(name, methods) { if (arguments.length != 2) { throw new Error("Interface constructor called with " + arguments.length + "arguments, but expected exactly 2."); }
this.name = name; this.methods = []; for (var i = 0, len = methods.length; i < len; i++) { if (typeof methods[i] !== 'string') { throw new Error("Interface constructor expects method names to be " + "passed in as a string."); } this.methods.push(methods[i]); } }; // 接口检查 Interface.ensureImplements = function(object) { if (arguments.length < 2) { throw new Error("Function Interface.ensureImplements called with " + arguments.length + "arguments, but expected at least 2."); }
for (var i = 1, len = arguments.length; i < len; i++) { var v_interface = arguments[i]; if (v_interface.constructor !== Interface) { throw new Error("Function Interface.ensureImplements expects arguments " + "two and above to be instances of Interface."); }
for (var j = 0, methodsLen = v_interface.methods.length; j < methodsLen; j++) { var method = v_interface.methods[j]; if (!object[method] || typeof object[method] !== 'function') { throw new Error("Function Interface.ensureImplements: object " + "does not implement the " + v_interface.name + " interface. Method " + method + " was not found."); } } } }; // 原形继承 function clone(object) { function F() { } F.prototype = object; return new F; }
// 抽象工厂 var AbstractFactory = (function() { // 抽象方法检查 function checkImplements(object) { var isContain = false; var v_method = ''; if (arguments.length < 2) { throw new Error("Function AbstractFactory.checkImplements called with " + arguments.length + "arguments, but expected at least 2."); } for (var i = 1; i < arguments.length; i++) { var v_AbstractClass = arguments[i]; for (key in v_AbstractClass) { if (!object[key] && typeof object[key] !== 'function' && key != 'getFactory') { isContain = true; v_method = key; break; } } } if (isContain) { throw new Error("Function AbstractFactory.ensureImplements: object " + "does not implement the AbstractFactory " + "AbstractCalss. AbstractMethod " + v_method + " was not found."); } } // 选择具体工厂 function chooesFactory(mode) { var factory = null; switch (mode) { case 'giant' : factory = GiantFactory; break; case 'cnforever' : factory = CnforeverFactory; break; case 'merida' : factory = MeridaFactory; break; default : throw new Error("mode not found"); } checkImplements(factory, AbstractFactory) return factory; } return { getFactory : function(mode) { return chooesFactory(mode); }, // 抽象方法 createBicycle : function() { throw new Error('Unsupported operation on an abstract class:createBicycle'); } } })(); // 继承 var GiantFactory = clone(AbstractFactory); GiantFactory = { // 实现父类抽象方法 createBicycle : function() { var giantBicycle = new GiantBicycle(); Interface.ensureImplements(giantBicycle, Bicycle); return giantBicycle; } }; // 创建接口 var Bicycle = new Interface("Bicycle", ['assemble', 'wash', 'ride', 'repair']); var GiantBicycle = function() {