JavaScript实现java中的|接口|继承|抽象类|继承|多态|对象|工厂模式|重写|重载|

时间:2022-05-06
本文章向大家介绍JavaScript实现java中的|接口|继承|抽象类|继承|多态|对象|工厂模式|重写|重载|,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
//定一个接口方法,
 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();