CommonUtil.js
/**
* @author Fan
*/
/**
* 命名空间
*/
var Fan = {};
//接口类
Fan.Interface = function(name,method){
//判断接口的个数
if(arguments.length != 2){
throw new Error('接口参数必须是2个');
}
this.name = name;
//创建一个空数组,存放method里的方法
this.method = [];
for(var i=0, len = method.length; i<len; i++){
if(typeof method[i] !== 'string'){
throw new Error('必须是字符串');
}
this.method.push(method[i]);
}
}
//校验接口的方法
Fan.Interface.ensureImplements = function(object){
if(arguments.length < 2){
throw new Error('参数不能小于2个');
}
//获得接口实例对象
for(var i=1, len = arguments.length; i<len; i++){
var instanceInterface = arguments[i];
//判断参数是接口类型
if(instanceInterface.constructor !== Fan.Interface){
throw new Error('必须是接口类型');
}
//循环接口里的每一个方法
for(var j=0; j< instanceInterface.method.length; j++){
//用一个临时变量,接受每一个方法的名字(注意是字符串)
var methodName = instanceInterface.method[j];
//Object[key]就是方法
if(!object[methodName] || typeof object[methodName] !== 'function'){
throw new Error('错误类型');
}
}
}
};
//继承方法
//参数1:子类
//参数2:父类
Fan.extend = function(sub,sup){
//实现只继承父类原型对象
var F = new Function(); //创建一个空函数,进行中转
F.prototype = sup.prototype; //实现空函数的原型对象,和父类原型对象的转换
sub.prototype = new F(); //子类原型对象继承
sub.prototype.constructor = sub; //还原子类的构造器
//保存一下父类原型对象,一方面方便解耦,另一方面获得父类的原型对象
sub.superClass = sup.prototype;
//判断父类原型构造器
if(sup.prototype.constructor == Object.prototype.constructor){
sup.prototype.constructor = sup;
}
}
index.js
//创建一个工厂的环境
//卖车的商店
function CarShop(){};
CarShop.prototype = {
constructor : CarShop, //还原构造器
sellCar : function(type){
var car;
switch (type) {
case 'Benz':
car = new Benz();
break;
case 'Bmw':
car = new Bmw();
break;
case 'Audi':
car = new Audi();
break;
default : 'not buy it';
}
//验证接口
Fan.Interface.ensureImplements(car , CarInterface);
return car;
}
}
//通过接口类,实例化一个接口对象
var CarInterface = new Fan.Interface('CarInterface',['start','run']);
//车类,宝马,奔驰,奥迪
function Benz(){};
Benz.prototype.start = function(){
console.log('Benz...start');
};
Benz.prototype.run = function(){
console.log('Benz...run');
};
function Bmw(){};
Bmw.prototype.start = function(){
console.log('Bmw...start');
};
Bmw.prototype.run = function(){
console.log('Bmw...run');
};
function Audi(){};
Audi.prototype.start = function(){
console.log('Audi...start');
};
Audi.prototype.run = function(){
console.log('Audi...run');
};
var shop = new CarShop();
var car = shop.sellCar('Benz');
car.start();
car.run();