您的位置:首页 > Web前端 > JavaScript

javascript 接口模拟的三中实现方式

2018-09-28 17:41 351 查看

javascript 接口模拟的三中实现方式

  • 三中方法:注释法,属性检查法,鸭式变型法
    注释法:
//注释法 定义接口类
/*
* interface  interfaceClass{
*   function eat(x,y)
*   function run(z)
* }
*
* */

var Person = function(){  //接口的实现类interfaceClass

};
Person.prototype.eat=function (x,y) {

}
Person.prototype.run=function (z) {

}

属性检查法

//属性检查法
/*
* interface  action{
*   function eat(x,y)
*   function run(z)
* }
*
* */
var Person = function(){  //实现接口类action
this.imlementsInterfaces=['action'];
};
Person.prototype.eat=function (x,y) {
console.log("实现了-"+x+y)
}
Person.prototype.run=function (z) {

}
function checkProperty(Obj) {
for(var i=1;i<arguments.length;i++){
var interfaceName = arguments[i];
var isFound = false;
for(var j=0;j<Obj.imlementsInterfaces.length;j++){
if(Obj.imlementsInterfaces[j]==interfaceName){
isFound = true;
break;
}

}
if(!isFound){
return false;
}
}
return true;
}

function personName(){
var action = new Person();
if(checkProperty(action,'action')){
console.log("实现了接口");
action.eat("水","食物")
}else{
console.log("没有实现接口");
}
}
personName();

鸭式变形法

//定义一个接口类
var Interface = function (name,methods) {
if(arguments.length!=2){
throw new Error('必须输入两个参数,当前个数'+arguments.length);
};
this.name = name; //接口名
this.methods = []; //函数名
for(var i=0;i<methods.length;i++){
if(typeof methods[i] !== 'string'){
throw new Error('方法名参数必须为string');
}else{
this.methods.push(methods[i]);
}

}
};
//定义静态方法,检验实现接口和实现类 参数object为实现类对象

Interface.ensureImplements = function (object) {
if(arguments.length<2){
throw new Error('必须输入两个参数,当前个数' + arguments.length);
return;
};
for(var i =1;i<arguments.length;i++){
var interface = arguments[i];
if(interface.constructor != Interface){
throw new Error("接口没有实现");
};
for(var j=0;j<interface.methods.length;j++){
var method = interface.methods[j];
if(!object[method] || typeof object[method]!=='function'){
throw new Error("接口名:"+interface.name+"方法名:"+method+"没找到");
}
}
}

};

//定义接口
var action = new Interface('action',['eat','run']);
var work = new Interface('work',['learn'])
//定义实现类
function actionFun() {
//实现接口的所有方法
this.eat = function () {
console.log("吃了");
};
this.run = function () {
console.log("跑了");
}
this.learn = function () {
console.log("学了");
}
Interface.ensureImplements(this,action,work);//检测是否实现接口方法
}
var p = new actionFun();
p.eat();
p.learn();
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: