Factory creates objects by providing a common interface, and we can also specify the type of object instances we want to create.
Suppose you now have a car factory vehiclefactory, which supports the creation of object instances of car and truck types and now requires the creation of objects of the specified type through this factory, then we do not need to create this specified object by directly using the new operator or through other creative constructors. , we just need to inform vehiclefactory what type of object instance we need, and then Vehiclefactory will return the object instance of the type we need.
Code implementation:
//constructors for car and trunkfunctionCar (options) { This. doors=options.doors| | 4; This. state=options.state| | " Brand new "; This. color=options.color| | " Black;}functionTrunk (options) { This. wheelsize=options.wheelsize| | ' Large; This. color=options.color| | " Yellow; This. state=options.state| | " Brand new ";}//Define Vehiclefactory Factoryfunctionvehiclefactory () {}//define how the factory creates instancesvehiclefactory.prototype.createvehicle=function(options) {Switch(options.vehicletype) { Case"Car": This. Vehicleclass=car; Break; Case"Trunk": This. Vehicleclass=trunk; Break; } return New This. Vehicleclass (options);};//Create a factory instance that generates a carLet carfactory=Newvehiclefactory (); let Car1=carfactory.createvehicle ({vehicletype:"Car", Color:"White", Doors:6}); Console.log (CAR1);//{doors:6,state: "Brand new", Color: "White"}
Common JavaScript Design Patterns (ii) Factory (factory) mode