标签:
设计工厂模式是为了创建对象。通常在类或者类的静态方法中实现,具有两个目标。其中一个是:当创建相似对象时执行重复操作:
另外一个目标是:编译时不知道具体类型(类)的情况下,为工厂客户提供一种创建对象的接口。
实现如下:
//父构造器 function CarMaker(){}
//在原型中添加共享的方法 CarMaker.prototype.drive = function(){ return "Vroom, I have "+ this.doors + " doors"; }; //静态工厂方法 CarMaker.factory = function(type){ var constr = type, newcar; //如果构造函数不存在,则发生错误 if(typeof CarMaker[constr] !== "function"){ throw { name:"error", message:constr + " doesn‘t exit" }; } //使得原型继承父类,仅继承了一次 if(typeof CarMaker[constr].prototype.drive !== "function"){ CarMaker[constr].prototype = new CarMaker(); } //创建一个实例 newcar = new CarMaker[constr](); return newcar; }; //定义特定的汽车构造商 CarMaker.Compact = function(){ this.doors = 4; }; CarMaker.Convertible = function(){ this.doors = 1; }; CarMaker.SUV = function(){ this.doors = 17; };
//test var compact = CarMaker.factory("Compact"); var convertible = CarMaker.factory("Convertible"); var suv = CarMaker.factory("SUV"); console.log(compact.drive()); //Vroom, I have 4 doors console.log(convertible.drive()); //Vroom, I have 1 doors console.log(suv.drive()); //Vroom, I have 17 doors
标签:
原文地址:http://www.cnblogs.com/scnuwangjie/p/5005740.html