zoukankan      html  css  js  c++  java
  • javascript设计模式【1】,接口Interface,鸭式辨型

     1 // 接口构造函数,name为接口名,methods为字符串数组表明接口需要实现的方法
     2 var Interface = function (name, methods)
     3 {
     4   if (arguments.length != 2)
     5   {
     6     throw Error("接口构造函数需要2个参数");
     7   } // end if
     8   this.name = name;
     9   this.methods = [];
    10   for (var i = 0, len = methods.length; i < len; ++i)
    11   {
    12     if (typeof methods[i] !== "string")
    13     {
    14       throw new TypeError("函数名应该使用字符串");
    15     } // end if
    16     this.methods.push(methods[i]);
    17   } // end for
    18 } // end Interface()
    19 
    20 // 类静态方法,用于检查接口,如果对象不满足接口需要,抛出异常
    21 Interface.ensureImplements = function (object/*[,Interface]* */)
    22 {
    23   if (arguments.length < 2)
    24   {
    25     throw new Error("方法需要最少两个实参,第一个为需要检查的对象,后续为多个需要检查的接口");
    26   } // end if
    27   for (var i = 1, len = arguments.length; i < len; ++i)
    28   {
    29     var item = arguments[i]; // 接口
    30     if (item.constructor !== Interface)
    31     {
    32       throw TypeError("需要检查的类型必须为接口");
    33     } // end if
    34     for (var j = 0, methodsLen = item.methods.length; j < methodsLen; ++j)
    35     {
    36       var method = item.method[j];
    37       if (!object[method] || typeof object[method] !== "function")
    38       {
    39         throw Error("对象没有实现:" + item.name + " 的 " + method + " 方法");
    40       } // end if
    41     } // end inner for
    42   } // end for
    43 } // end ensureImplements()

    接口使用。检查对象能做什么。而不关心它是什么。

  • 相关阅读:
    H5及微信中唤起app的解决方案
    html5统计数据上报API:SendBeacon
    基于webpack4的react开发环境配置
    electron-vue开发爬坑指南
    利用git 进行多人协作开发
    js 性能优化利器:prepack
    各种渲染方式对比解析
    Nuxt.js部署应用的方式
    微信小程序--data的赋值与取值
    甘超波:什么是个人定位
  • 原文地址:https://www.cnblogs.com/qiudeqing/p/3418410.html
Copyright © 2011-2022 走看看