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 相关文章推荐
JS实现从连接中获取youtube的key实例
Jul 02 Javascript
动态创建按钮的JavaScript代码
Jan 29 Javascript
AngulaJS路由 ui-router 传参实例
Apr 28 Javascript
vue-cli脚手架config目录下index.js配置文件的方法
Mar 13 Javascript
详解如何在你的Vue项目配置vux
Jun 04 Javascript
如何在Angular应用中创建包含组件方法示例
Mar 23 Javascript
JS去除字符串最后的逗号实例分析【四种方法】
Jun 20 Javascript
详解Vue.js和layui日期控件冲突问题解决办法
Jul 25 Javascript
ES6学习笔记之let与const用法实例分析
Jan 22 Javascript
基于jsbarcode 生成条形码并将生成的条码保存至本地+源码
Apr 27 Javascript
JS数组转字符串实现方法解析
Sep 04 Javascript
vue-simple-uploader上传成功之后的response获取代码
Sep 07 Javascript
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
PHPLog php 程序调试追踪工具
2009/09/09 PHP
php实现三级级联下拉框
2016/04/17 PHP
项目中应用Redis+Php的场景
2016/05/22 PHP
javascript学习笔记(四) Number 数字类型
2012/06/19 Javascript
js获取RadioButtonList的Value/Text及选中值等信息实现代码
2013/03/05 Javascript
Jquery post传递数组方法实现思路及代码
2013/04/28 Javascript
基于Vue.js的表格分页组件
2016/05/22 Javascript
js简单获取表单中单选按钮值的方法
2016/08/23 Javascript
javascript表单正则应用
2017/02/04 Javascript
vue-resource 拦截器(interceptor)的使用详解
2017/07/04 Javascript
js实现登录注册框手机号和验证码校验(前端部分)
2017/09/28 Javascript
JS的Ajax与后端交互数据的实例
2018/08/08 Javascript
vue开发拖拽进度条滑动组件
2019/09/21 Javascript
node.JS事件机制与events事件模块的使用方法详解
2020/02/06 Javascript
Openlayers显示瓦片网格信息的方法
2020/09/28 Javascript
[08:08]DOTA2-DPC中国联赛2月28日Recap集锦
2021/03/11 DOTA
Python(Tornado)模拟登录小米抢手机
2013/11/12 Python
详解Python中find()方法的使用
2015/05/18 Python
python实现多层感知器
2019/01/18 Python
详解Python列表赋值复制深拷贝及5种浅拷贝
2019/05/15 Python
pycharm新建一个python工程步骤
2019/07/16 Python
关于python3.7安装matplotlib始终无法成功的问题的解决
2020/07/28 Python
Python调用Redis的示例代码
2020/11/24 Python
ASOS英国官网:英国在线时装和化妆品零售商
2017/05/19 全球购物
阿根廷首家户外用品制造商和经销商:Montagne
2018/02/12 全球购物
迪斯尼假期(欧洲、中东及非洲):Disney Holidays EMEA
2021/02/15 全球购物
成龙洗发水广告词
2014/03/14 职场文书
初三学生个人自我评定
2014/04/06 职场文书
我是一名护士演讲稿
2014/08/28 职场文书
财务会计实训报告
2014/11/05 职场文书
2015教师见习期工作总结
2014/12/12 职场文书
员工评语范文
2014/12/31 职场文书
小学英语教学经验交流材料
2015/11/02 职场文书
2016年学校党支部公开承诺书
2016/03/25 职场文书
简历中的自我评价应该这样写!
2019/07/12 职场文书
Mysql 设置boolean类型的操作
2021/06/04 MySQL