/** Code copyright Dustin Diaz and Ross Harmes, Pro JavaScript Design Patterns. **/ // Constructor. var Interface = function (name, methods) { if (arguments.length !== 2) { thrownewError("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') { thrownewError("Interface constructor expects method names to be " + "passed in as a string."); } this.methods.push(methods[i]); } };
// Static class method. Interface.ensureImplements = function (object) { if (arguments.length < 2) { thrownewError("Function Interface.ensureImplements called with " + arguments.length + "arguments, but expected at least 2."); } for (var i = 1, len = arguments.length; i < len; i++) { var interface = arguments[i]; if (interface.constructor !== Interface) { thrownewError("Function Interface.ensureImplements expects arguments" + "two and above to be instances of Interface."); } for (var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) { var method = interface.methods[j]; if (!object[method] || typeof object[method] !== 'function') { thrownewError("Function Interface.ensureImplements: object " + "does not implement the " + interface.name + " interface. Method " + method + " was not found."); } } } };
var reminder = new Interface("List", ["summary", "placeOrder"]);
var properties = { name: "Remember to buy the milk", date: "05/06/2016", actions: { summary: function () { return"Remember to buy the milk, we are almost out"; }, placeOrder: function () { return"Ordering milk from your local grocery store"; } } };
// 创建 todo 构造函数的新实例 var todoItem = new Todo(properties);
// 最后测试确保新增加的功能可用 // 输出:Remember to buy the milk, we are almost out console.log(todoItem.methods.summary()); // 输出:Remember to buy the milk, we are almost out console.log(todoItem.methods.placeOrder());
var MacbookWith4GBRam = function(){}; var MacbookWith8GBRam = function(){}; var MacbookWith4GBRamAndEngraving = function(){}; var MacbookWith8GBRamAndEngraving = function(){}; var MacbookWith4GBRamAndParallels = function(){}; var MacbookWith8GBRamAndParallels = function(){}; var MacbookWith4GBRamAndParallelsAndCase = function(){}; var MacbookWith8GBRamAndParallelsAndCase = function(){}; var MacbookWith4GBRamAndParallelsAndCaseAndInsurance = function(){}; var MacbookWith8GBRamAndParallelsAndCaseAndInsurance = function(){}; // etc ...