Factory mode
The purpose of the factory schema design is to create objects. It is usually implemented in a static method of a class or class, with the following objectives:
1. Perform a repeat operation when creating a similar object
2. Provide the factory customer with an interface to create objects at compile time without knowing the specific type (class).
Objects created through factory methods (or classes) are designed to inherit the same idea of the same parent object, which are specific subclasses that implement specialized functionality. Sometimes the public parent class is the same class that contains the factory method,
Code:
//Parent Constructorfunctioncarmaker () {}; CarMaker.prototype.drive=function(){ return' Vroom, I have ' + This. Doors + ' doors ';};//Static Factory MethodCarmaker.factory =function(type) {varConstr =type, Newcar; //if the constructor does not exist, an error occurs if(typeofCARMAKER[CONSTR]!== ' function '){ Throw{name:' Error ', Message:constr+ "doesn ' t exist" } } //causes the prototype to inherit from the parent class, but inherits only once if(typeofCarmaker[constr].prototype.drive!== ' function ') {Carmaker[constr].prototype=Newcarmaker (); } //to create a new instanceNewcar =NewCarmaker[constr] (); //Optionally call some methods and return .... returnNewcar;};//define a specific car makerCarmaker.compact =function(){ This. Doors = 4;} Carmaker.convertible=function(){ This. Doors = 2;}; CARMAKER.SUV=function(){ This. Doors = 24;};varCorolla = Carmaker.factory (' Compact ');varSolstice = carmaker.factory (' convertible '));varCherokee = carmaker.factory (' SUV ')); Console.log (Corolla.drive ()); //The result is ' Vroom, I have 4 Doors 'Console.log (Solstice.drive ());//The result is ' Vroom, I have 2 Doors 'Console.log (Cherokee.drive ());//results for ' Vroom, I have doors '