2.02 - emulating interfaces with attribute checking.js
来自「JS设计模式源代码」· JavaScript 代码 · 共 50 行
JS
50 行
/*interface Composite { function add(child); function remove(child); function getChild(index);}interface FormItem { function save();}*/var CompositeForm = function(id, method, action) { this.implementsInterfaces = ['Composite', 'FormItem']; ...};...function addForm(formInstance) { if(!implements(formInstance, 'Composite', 'FormItem')) { throw new Error("Object does not implement a required interface."); } ...}// The implements function, which checks to see if an object declares that it // implements the required interfaces.function implements(object) { for(var i = 1; i < arguments.length; i++) { // Looping through all arguments // after the first one. var interfaceName = arguments[i]; var interfaceFound = false; for(var j = 0; j < object.implementsInterfaces.length; j++) { if(object.implementsInterfaces[j] == interfaceName) { interfaceFound = true; break; } } if(!interfaceFound) { return false; // An interface was not found. } } return true; // All interfaces were found.}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?