//定一个接口方法,
var Interface = function(name,methods){
if(arguments.length != 2){
throw new Error('this instance interface constructor arguments must be 2 length!');
}
this.name = name ;
this.methods = [] ;
for(var i = 0,len = methods.length ; i <len ; i++){
if( typeof methods[i] !== 'string'){
throw new Error('the Interface method name is error!');
}
this.methods.push(methods[i]);
}
}
Interface.ensureImplements = function(object){
if(arguments.length < 2 ){
throw new Error('Interface.ensureImplements method constructor arguments must be >= 2!');
}
for(var i = 1 , len = arguments.length; i<len; i++ ){
var instanceInterface = arguments[i];
if(instanceInterface.constructor !== Interface){
throw new Error('the arguments constructor not be Interface Class');
}
for(var j = 0 ; j < instanceInterface.methods.length; j++){
var methodName = instanceInterface.methods[j];
if( !object[methodName] || typeof object[methodName] !== 'function' ){
throw new Error("the method name '" + methodName + "' is not found !");
}
}
}
}
//定义一个继承的方法
var self_extend=function(child,parent){//原型继承方法,如需继承非原型方法,用parent_obj.call(this,())//还能实现多继承
var F = new Function();
F.prototype=parent.prototype;
child.prototype=new F();
child.prototype.constructor=child;
child.superClass=parent.prototype;
if(parent.prototype.constructor==Object.prototype.constructor){
parent.prototype.constructor=parent;
}
}
var create_car={//车的工厂类
create_car:function(type){
var car=eval('new '+type+' () ');//多态
Interface.ensureImplements(car,car_interface)
return car;
}
}
function car_shop(){//买车的父类
}
car_shop.prototype={
constructor:car_shop,
sell_car:function(type){
this.abstract_sell_car(type);
},
abstract_sell_car:function(){//抽象方法,子类实现
throw new Error("this method is abstract");
}
}
function benz_car_shop(){//各类汽车店,重写父类的方法
}
self_extend(benz_car_shop,car_shop);
benz_car_shop.prototype={
constructor:benz_car_shop,
sell_car:function(type){//覆盖父类的方法
var car;
var types=["benz"];
for(t in types){
if(types[t]===type){
car = create_car.create_car(type);
}else{
throw new Error("车店没有类型");
}
}
return car;
}
}
//车实现两个方法,然后四种子类汽车继承
var car_interface=new Interface('car_interface',["start","run"]);
function base_car(){
}
base_car.prototype={
constructor:base_car,
start:function(){
console.log(this.constructor.name+" this is start")
},
run:function(){
console.log("this is running")
}
}
function benz(){};
self_extend(benz,base_car);//继承父类
benz.prototype.drive_benz=function(){
console.log("benz driver");
}
function bwm(){};
self_extend(bwm,base_car);
function audi(){};
self_extend(audi,base_car);
var shop1=new benz_car_shop();
var car1=shop1.sell_car("benz");//多态
car1.start();
本文分享自 交互设计前端开发与后端程序设计 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体分享计划 ,欢迎热爱写作的你一起参与!