The Factory mode (Factory) provides a common interface to create objects.
If you have a UI library, we want to create a type of UI component that does not need to be created directly using the new operator or through another create-type constructor, but rather requires the factory object to create a new component. We tell factory what kind of object (such as a button, panel) it needs, it instantiates it, and then returns it to us.
functionCar (name, color) { This. Name =name; This. color =color;}functionTrunk (name, color) { This. Name =name; This. color =color;}functionvehiclefactory () {}vehiclefactory.prototype.vehicleclass= Car;//Add default TypeVehicleFactory.prototype.createVehicle =function(name, color) {if(name = = = ' car ')) { This. Vehicleclass =Car; } Else { This. Vehicleclass =Trunk; } return Newvehicleclass (name, color);} Let Factory=Newvehiclefactory () Let car= factory.createvehicle (' car ', ' red ') Console.log (carinstanceofCar)//Truelet trunk= factory.createvehicle (' trunk ', ' blank ') Console.log (trunkinstanceofTrunk)//True
JavaScript design Pattern---(Factory mode learning)