javascript设计模式 接口介绍


Posted in Javascript onJuly 24, 2012

这本书中第一个重要的内容就是接口。

大家对接口应该都不陌生,简单的说接口就是一个契约或者规范。在强类型的面相对象语言中,接口可以很容易的实现。但是在javascript中并没有原生的创建或者实现接口的方式,或者判定一个类型是否实现了某个接口,我们只能利用js的灵活性的特点,模拟接口。
在javascript中实现接口有三种方式:注释描述、属性验证、鸭子模型。
note:因为我看的是英文书,翻译水平有限,不知道有些词汇如何翻译,大家只能领会精神了。
1. 注释描述 (Describing Interfaces with Comments)
例子:

/* 
interface Composite { 
function add(child); 

function remove(child); 

function getChild(index); 
} 
interface FormItem { 

function save(); 
} 
*/ 
var CompositeForm = function(id, method, action) { // implements Composite, FormItem 

... 
}; 
//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() { 
... 
};

模拟其他面向对象语言,使用interface 和 implements关键字,但是需要将他们注释起来,这样就不会有语法错误。
这样做的目的,只是为了告诉其他编程人员,这些类需要实现什么方法,需要在编程的时候加以注意。但是没有提供一种验证方式,这些类是否正确实现了这些接口中的方法,这种方式就是一种文档化的作法。
2. 属性验证(Emulating Interfaces with Attribute Checking)
例子:
/* 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. 
}

这种方式比第一种方式有所改进,接口的定义仍然以注释的方式实现,但是添加了验证方法,判断一个类型是否实现了某个接口。
3.鸭子类型(Emulating Interfaces with Duck Typing)
// 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(formInstance) { 

ensureImplements(formInstance, Composite, FormItem); 

// This function will throw an error if a required method is not implemented. 

... 
} 
// Constructor. 
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]); 

} 
}; 
// Static class method. 
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 interface = arguments[i]; 


if(interface.constructor !== Interface) { 



throw new Error("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') { 




throw new Error("Function Interface.ensureImplements: object " 








+ "does not implement the " + interface.name + " interface. Method " + method + " was not found."); 



} 


} 

} 
};

何时使用接口?
一直使用严格的类型验证并不适合,因为大多数javascript程序员已经在没有接口和接口验证的情况下编程多年。当你用设计模式开始设计一个很复杂的系统的时候,使用接口更有益处。看起来使用接口好像限制了javascript的灵活性,但实际上他让你的代码变得更加的松耦合。他使你的代码变得更加灵活,你可以传送任何类型的变量,并且保证他有你想要的方法。有很多场景接口非常适合使用。
在一个大型系统里,很多程序员一起参与开发项目,接口就变得非常必要了。程序员经常要访问一个还没有实现的api,或者为其他程序员提供别人依赖的一个方法存根,在这种情况下,接口变得相当的有价值。他们可以文档化api,并作为编程的契约。当存根被实现的api替换的时候你能立即知道,如果在开发过程中api有所变动,他能被另一个实现该接口的方法无缝替换。
如何使用接口?
首先要解决的问题是,在你的代码中是否适合使用接口。如果是小项目,使用接口会增加代码的复杂度。所以你要确定使用接口的情况下,是否是益处大于弊端。如果要使用接口,下面有几条建议:
1.引用Interface 类到你的页面文件。interface的源文件你可以再如下站点找到: http://jsdesignpatterns.com/.
2.检查你的代码,确定哪些方法需要抽象到接口里面。
3.创建接口对象,没个接口对象里面包含一组相关的方法。
4.移除所有构造器验证,我们将使用第三种接口实现方式,也就是鸭子类型。
5.用Interface.ensureImplements替代构造器验证。
Javascript 相关文章推荐
jquery图片播放浏览插件prettyPhoto使用详解
Dec 19 Javascript
jQuery实现设置、移除文本框默认值功能
Jan 13 Javascript
jquery easyui datagrid实现增加,修改,删除方法总结
May 25 Javascript
JS Array创建及concat()split()slice()的使用方法
Jun 03 Javascript
node.js学习之断言assert的使用示例
Sep 28 Javascript
基于cropper.js封装vue实现在线图片裁剪组件功能
Mar 01 Javascript
Egg.js 中 AJax 上传文件获取参数的方法
Oct 10 Javascript
关于微信公众号开发无法支付的问题解决
Dec 28 Javascript
详解微信小程序-canvas绘制文字实现自动换行
Apr 26 Javascript
Vue中this.$nextTick的作用及用法
Feb 04 Javascript
在vant 中使用cell组件 定义图标该图片和位置操作
Nov 02 Javascript
Vue OpenLayer 为地图绘制风场效果
Apr 24 Vue.js
javascript设计模式 封装和信息隐藏(上)
Jul 24 #Javascript
js+xml生成级联下拉框代码
Jul 24 #Javascript
40个新鲜出炉的jQuery 插件和免费教程[上]
Jul 24 #Javascript
基于jquery的跟随屏幕滚动代码
Jul 24 #Javascript
基于JQuery的类似新浪微博展示信息效果的代码
Jul 23 #Javascript
基于jquery自定义图片热区效果
Jul 21 #Javascript
Js四则运算函数代码
Jul 21 #Javascript
You might like
phpmailer绑定邮箱的实现方法
2016/12/01 PHP
php7安装yar扩展的方法详解
2017/08/03 PHP
Jquery 获得服务器控件值的方法小结
2010/05/11 Javascript
js鼠标点击事件在各个浏览器中的写法及Event对象属性介绍
2013/01/24 Javascript
jquery validation验证身份证号,护照,电话号码,email(实例代码)
2013/11/06 Javascript
JavaScript数组去重的3种方法和代码实例
2015/07/01 Javascript
浅析nodejs实现Websocket的数据接收与发送
2015/11/19 NodeJs
animate 实现滑动切换效果【实例代码】
2016/05/05 Javascript
jQuery autoComplete插件两种使用方式及动态改变参数值的方法详解
2016/10/24 Javascript
详解js树形控件—zTree使用总结
2016/12/28 Javascript
vue实现ajax滚动下拉加载,同时具有loading效果(推荐)
2017/01/11 Javascript
webpack公共组件引用路径简化小技巧
2018/06/15 Javascript
Vue.js实现tab切换效果
2019/07/24 Javascript
Object.keys() 和 Object.getOwnPropertyNames() 的区别详解
2020/05/21 Javascript
js简单实现自动生成表格功能示例
2020/06/02 Javascript
解决vue项目,npm run build后,报路径错的问题
2020/08/13 Javascript
Python时间戳与时间字符串互相转换实例代码
2013/11/28 Python
详解windows python3.7安装numpy问题的解决方法
2018/08/13 Python
Python异常处理操作实例详解
2018/08/28 Python
python使用threading.Condition交替打印两个字符
2019/05/07 Python
python循环定时中断执行某一段程序的实例
2019/06/29 Python
Python3 main函数使用sys.argv传入多个参数的实现
2019/12/25 Python
Python TCPServer 多线程多客户端通信的实现
2019/12/31 Python
解决pyqt5异常退出无提示信息的问题
2020/04/08 Python
详解Django配置JWT认证方式
2020/05/09 Python
Python调用JavaScript代码的方法
2020/10/27 Python
HTML5自定义元素播放焦点图动画的实现
2019/09/25 HTML / CSS
加拿大户外探险购物网站:SAIL
2020/06/27 全球购物
生日庆典策划方案
2014/06/02 职场文书
查摆剖析材料范文
2014/09/30 职场文书
乱丢垃圾袋检讨书
2014/10/08 职场文书
工伤死亡理赔协议书
2014/10/20 职场文书
2015年高校教师个人工作总结
2015/05/25 职场文书
pytorch 一行代码查看网络参数总量的实现
2021/05/12 Python
详解Python为什么不用设计模式
2021/06/24 Python
python pygame 开发五子棋双人对弈
2022/05/02 Python