3-JavaScript设计模式——commonUtils工具库之接口类

在学习 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);

结果:



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值