在学习 JavaScript 设计模式之前,我们先做一个 commonUtils 工具库,以便于后期的学习和使用。
结果:
commonUtils 工具库包括:多维数组遍历,继承函数,接口类及其验证。
本章为接口类
建立接口的方式:
1、注解描述法:优点 使用简单,程序员可以有一个参考;缺点:它只是一个注释,属于文档的范畴,是功能最弱的一种方式。
2、属性检测法:优点 比注解描述法功能强大;缺点 不能检测接口中的方法。
3、鸭式辩型法:最完美的实现接口方式,很多大型框架底层都采用“鸭式辩型法”。
下面是 鸭式辩型法
// 命名空间
var JG = {};
// 一、接口类 完全面向对象,代码统一,解耦
/*
接口类需要两个参数:
参数1:接口的名字
参数2:接收方法名称的集合(数组)
*/
JG.Interface = function(name, methods){
// 判断接口的参数个数
if(arguments.length != 2){
throw new Error('this instance interface constructor arguments.length must be 2!');
}
this.name = name;
// 定义一个内置空数组对象,当传递的参数 methods 的成员符合条件时,才将 methods 成员(方法名字)添加到内置空数组对象 this.methods 中
this.methods = [];
for(var i = 0, len = methods.length; i < len; i++){
if(typeof methods[i] !== 'string'){
throw new Error('the Interface method name is error!');
}
this.methods.push(methods[i]);
}
};
// 实例化接口对象
var CompositeInterface = new JG.Interface('CompositeInterface', ['add', 'remove']);
var FormItemInterface = new JG.Interface('FormItemInterface', ['update', 'select']);
// 二、准备工作,具体的实现类
var CompositeImpl = function(){
};
CompositeImpl.prototype.add = function(){
alert('add...');
};
CompositeImpl.prototype.remove = function(){
alert('remove...');
};
CompositeImpl.prototype.update = function(){
alert('update...');
};
// CompositeImpl.prototype.select = function(){
// alert('select...');
// };
// 三、检验接口里面的方法
// 如果检验通过,不做任何操作;不通过:浏览器抛出异常error
JG.Interface.ensureImplements = function(object){
if(arguments.length < 2){
throw new Error('JG.Interface.ensureImplements method constructor arguments.length must be more then 2!');
}
// 获得接口实例对象
for(var i = 1, len = arguments.length; i < len; i++){
var instanceInterface = arguments[i];
// 判断参数是否是接口类的类型
if(instanceInterface.constructor !== JG.Interface){
throw new Error('the ' + instanceInterface + ' is not a JG.Interface instance');
}
// 循环接口实例对象里面的每一个方法
for(var j = 0; j < instanceInterface.methods.length;j++){
// 用一个临时变量 接收每一个方法的名字(注意是字符串)
var methodName = instanceInterface.methods[j];
// object[key]就是方法
if(!object[methodName] || typeof object[methodName] !== 'function'){
throw new Error('the method "' + methodName + '" is not found...');
}
}
}
};
// 实例化实现类
var c1 = new CompositeImpl();
JG.Interface.ensureImplements(c1, CompositeInterface, FormItemInterface);
结果: