Software_Programming_DP_JS
2020-01-01 16:15:14
Factory Pattern
- 公共父构造函数
- 一个名为 factory() 的 CarMaker 的静态方法, 该方法创建 car 对象
- 从 CarMaker 继承的专门构造函数都被定义为父类的静态属性,以便保证全局命名空间免受污染,便于定位
工厂方法接受在运行时以字符串形式指定的类型,然后创建并返回所请求类型的对象。
代码中看不到任何具有new或对象字面量的构造函数,其中仅有一个函数根据字符串所指定类型来创建对象。
1 // 父构造函数 2 function CarMaker(){} 3 4 // 父类的一个方法 5 CarMaker.prototype.drive = function(){ 6 return "Vroom, I have " + this.doors + " doors"; 7 }; 8 9 // 静态工厂方法 10 CarMaker.factory = function(type){ 11 var constr = type, newCar; 12 13 // 如果构造函数不存在,则发生错误 14 if(typeof CarMaker[constr] !== "function"){ 15 throw{ 16 name: "Error", 17 message: constr + " doesn`t exist" 18 }; 19 } 20 21 // 在这里,构造函数是存在的,前面已拦截不存在情况 22 // 使原型继承父类,但仅继承一次 23 if(typeof CarMaker[constr].prototype.drive !== "function"){ 24 CarMaker[constr].prototype = new CarMaker(); 25 } 26 27 // 创建一个新的实例 28 newCar = new CarMaker[constr](); 29 30 // 可选择性的调用一些方法然后返回。 31 32 return newCar; 33 };
// 定义特定的子类 CarMaker.Compact = function(){ this.doors = 4; } CarMaker.Convertible = function(){ this.doors = 2; } CarMaker.SUV = function(){ this.doors = 24; }
使用示例