您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JavaScript设计模式之一Interface接口

2025/9/5 2:10:07发布15次查看
如何用面向对象的思想来写javascript,对于初学者应该是比较难的,我们经常用的jquery其实也是用面向对象的思想去封装的,今天我们来看看如何在javascript中用interface,在c#还是java中都应该面向接口设计我们的程序,在c#和java中都interface这样的关键字,但是javascript中没有相应的机制,但是javascript很灵活,我们可以用它的特性去模仿interface,但是我们需要加入一些methods来做check的动作。
我们来看下一个interface的作用: 
继承了这个interface就必须要实现这个interface中定义的方法(方法签名)
//javascript 现在还做不到方法的签名的约束
var interface = function (name, methods) {     
   if (arguments.length != 2) {     
      throw new error(the interface length is bigger than 2);      
  }      
  this.name = name;     
   this.method = [];     
   for (var i = 0; i < methods.length; i++) {  
      if(typeof methods[i]!== string) {    
    throw new error(the method name is not string);    
    }        this.method.push(methods[i]);   
     }   
 }  
  /*static method in interface*/  
  interface.ensureimplement = function (object) {  
      if (arguments.length < 2) { 
           throw new error(there is not interface or the instance); 
       }       
 for (var i = 1; i < arguments.length; i++) {  
          var interface1 = arguments[i];      
      if (interface1.constructor !== interface) {               
 throw new error(the argument is not interface);           
 }            
for (var j = 0; j < interface1.method.length; j++) {               
 var method = interface1.method[j];               
 if (!object[method] || typeof object[method] !== function) {                  
  throw new error(you instance doesnt implement the interface);                                 
  }          
  }     
   }   
 }
我们来分析一下code,我们现在的做法是用来比较一个instance中的方法名在接口中是否定义了。
我先定义一个接口(2个参数),第二个参数是接口中的方法名。check方法用简单的2层for循环来做比较动作。
我们来看下如何去用这个接口:
 var person = new interface(person, [getname, getage]);      var man = function (name, age) {        this.name = name;        this.age = age;    }    man.prototype = { getname: function () { return this.name; },      //  getage: function () { return this.age; }    }    var test = function (instance) {               interface.ensureimplement(instance, person);           var name = instance.getname();        alert(name);    }    test(new man(alan,20));
如果我们注释了上面的getage方法,在执行的时候就会出错。在ensureimplement的时候发现并没有去实现这个方法。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product