zoukankan      html  css  js  c++  java
  • js接口的实现

    // Interface 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(obj){
      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(!obj[method] || typeof obj[method] != 'function'){
            throw new Error("Function Interface.ensureImplements: object "+
            "does not implement the "+interface.name+" interface.Method"+
            method+" was not found.");
          }
        }
      }
    };

     

    采用注释法和鸭式辨型法相结合的方式

    //Interfaces
    var Composite = new Interface('Composite',['add','remove','getChild']);
    var FormItem = new Interface('FormItem',['save']);
    
    //CompositeForm class
    var CompositeForm = function(id,method,action){//implements Composite,FormItem
      ...
    }
    ...
  • 相关阅读:
    Mysql高级第一天(laojia)
    Mysql初级第三天(wangyun)
    Mysql初级第二天(wangyun)
    Mysql初级第一天(wangyun)
    Spring的源码解析
    JAVA8新特性
    java8
    JMM内存模型
    JAVA并发工具类
    mybatis
  • 原文地址:https://www.cnblogs.com/byronvis/p/4514292.html
Copyright © 2011-2022 走看看