官术网_书友最值得收藏!

  • JavaScript:Moving to ES2015
  • Ved Antani Simon Timms Narayan Prusty
  • 356字
  • 2021-07-09 19:07:38

The factory pattern

The factory pattern is another popular object creation pattern. It does not require the usage of constructors. This pattern provides an interface to create objects. Based on the type passed to the factory, that particular type of object is created by the factory. A common implementation of this pattern is usually using a class or static method of a class. The purposes of such a class or method are as follows:

  • It abstracts out repetitive operations when creating similar objects
  • It allows the consumers of the factory to create objects without knowing the internals of the object creation

Let's take a common example to understand the usage of a factory. Let's say that we have the following:

  • A constructor, CarFactory()
  • A static method in CarFactory called make() that knows how to create objects of the car type
  • Specific car types such as CarFactory.SUV, CarFactory.Sedan, and so on

We want to use CarFactory as follows:

var golf = CarFactory.make('Compact');
var vento = CarFactory.make('Sedan');
var touareg = CarFactory.make('SUV');

Here is how you would implement such a factory. The following implementation is fairly standard. We are programmatically calling the constructor function that creates an object of the specified type—CarFactory[const].prototype = new CarFactory();.

We are mapping object types to the constructors. There can be variations in how you can go about implementing this pattern:

// Factory Constructor
function CarFactory() {}
CarFactory.prototype.info = function() {
  console.log("This car has "+this.doors+" doors and a "+this.engine_capacity+" liter engine");
};
// the static factory method
CarFactory.make = function (type) {
  var constr = type;
  var car;
  CarFactory[constr].prototype = new CarFactory();
  // create a new instance
  car = new CarFactory[constr]();
  return car;
};

CarFactory.Compact = function () {
  this.doors = 4;
  this.engine_capacity = 2; 
};
CarFactory.Sedan = function () {
  this.doors = 2;
  this.engine_capacity = 2;
};
CarFactory.SUV = function () {
  this.doors = 4;
  this.engine_capacity = 6;
}; 
  var golf = CarFactory.make('Compact');
  var vento = CarFactory.make('Sedan');
  var touareg = CarFactory.make('SUV');
  golf.info(); //"This car has 4 doors and a 2 liter engine"

We suggest that you try this example in JS Bin and understand the concept by actually writing its code.

主站蜘蛛池模板: 鄂托克旗| 宁国市| 耿马| 马公市| 瑞安市| 名山县| 阳曲县| 抚顺市| 友谊县| 焦作市| 凌源市| 呼和浩特市| 渝中区| 隆子县| 高邑县| 女性| 特克斯县| 尉氏县| 泾阳县| 英德市| 潼南县| 桐庐县| 高雄县| 宁明县| 宁安市| 武清区| 神木县| 广丰县| 灵寿县| 平阴县| 彭水| 张家界市| 蒙城县| 高要市| 墨玉县| 长乐市| 武冈市| 石河子市| 宁德市| 井陉县| 通辽市|