在Javascript中模仿接口(一)
2012-09-22 12:27 Barret李靖 阅读(318) 评论(0) 编辑 收藏 举报本文从ITeye导入
在JavaScript中模仿接口——本文摘自《JavaScript设计模式》
一、用注释描述接口
/* interface Composite { function add(child); function remove(child); function getChild(index); } interface FormItem { function save(); } */ var CompositeForm = function(id, method, action){ //...... }; //Implement the Composite interface. CompositeForm.prototype.add = function(child){ //...... } CompositeForm.prototype.remove = function(child){ //...... } CompositeForm.prototype.getChild = function(index){ //...... } ///Implement the FormItem interface. CompositeForm.prototype.save = function(){ //...... }
这种模仿并不是很好,他们有为确保CompositeForm真正实现正确的方法集而进行检查,
也不会跑出错误以高质程序员程序中的问题。
二、用属性检查模仿接口
/* 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 delcares that it //implements the required interfaces. function implements(object){ for(var i = 0; i < arguments.length; i++){ var interfaceName = arguments[i]; var interfaceFound = false; for(var j = 0; j < object.implementsInterface.length; j++){ if(object.implementsInterface[j] == interfaceName){ interfaceFound = true; break; } } if(!interfaceFound){ return false; //An interface was not found. } } return true; //All interface were found. }
在这个例子中,CompositeForm宣传自己实现了Composite和FormItem这两个接口,其做法是吧这链各个接口的
名称加入一个名为implement上Interfaces的数组。
三、用鸭式辨型模仿接口
//Interfaces var composite = new Interface('Composite', ['add', 'remove', 'getChild']); var FormItem = new Interface('FormItem', ['save']); //CompositeForm class var CompositeForm = function(id, method, action){ //........ } function addForm(formInstancd){ ensureImplements(formInstance, Composite, FormItem); //........ }
待续……

版权声明: 署名-非商业性使用-禁止演绎 3.0 国际(CC BY-NC-ND 3.0)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义