JS定义接口的方式 part2

<!DOCTYPE html>
<html>
<head>
<title>JS定义接口的方式 part2</title>
</head>
<body>


<script type="text/javascript">


//  鸭式辩型法(最完美的javascript实现接口方式)
// 注解描述法,属性检测法
// 


// 1. 接口类 class Interface ==> 目的:实例化N多接口
// 接口类需要两个参数,1.接口名称 2.接收方法的名字合集(数组)


var Interface = function (name, methods) {
// 判断接口的参数个数
if (arguments.length != 2) {
throw new Error('This instance Interface constructor arguments must be 2 length!');
}
this.name = name;
this.methods = []; // 定义一个内置的空数组对象,等待接受methods里的元素(方法名字)
for(i = 0; i < methods.length; i++) {
if(typeof methods[i] !== 'string') {
throw new Error('the interface method name is error!');
}
this.methods.push(methods[i]);
}
}


// 2.准备工作 
// (1)创建接口实例


var CompositeInterface = new Interface('CompositeInterface',['add','remove']);
var FormItemInterface = new Interface('FormItemInterface',['update','select']);





// (2)具体实现类


var CompositeImpl = function() {


}


// (3)实现接口代码


CompositeImpl.prototype.add = function() {
alert('add');
}
CompositeImpl.prototype.remove = function() {
alert('remove');
}
CompositeImpl.prototype.update = function() {
alert('update');
}
CompositeImpl.prototype.select = function() {
alert('select');
}


// 3.检验接口里的方法
// 如果检验通过,不执行操作;若不通过,浏览器抛出异常
Interface.ensureImplements = function(object) {
// 若检测参数小于2,则参数传递失败
if(arguments.length < 2) {
throw new Error('Interface.ensureImplements method constructor arguments must be > = 2');
}


// 获得接口实例对象
for (i = 1; i<arguments.length; i++) {
var instanceInterface = arguments[i];
// 判断参数是否是接口类的对象类型
if(instanceInterface.constructor !== Interface) {
throw new Error('the arguments constructor is not Interface class');
}
// 循环接口实例对象里的每一个方法
for (var j=0; j<instanceInterface.methods.length; j++) {
// 用临时变量接受每个方法的名字,注意是字符串
var methodName = instanceInterface.methods[j];
if (typeof object[methodName] !== 'function' || !object [methodName]) {
throw new Error('the method '+methodName+' is not found!');
}
}
}
}


var c1 = new CompositeImpl();
Interface.ensureImplements(c1, CompositeInterface, FormItemInterface);
c1.add();




// 总结接口


/*
1. 注解
2. 属性检测
3. 鸭式辩型


使用接口主要目的是解耦,对于中小型程序用处不大,甚至增加开发负担。
*/


</script>


</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值