What is a factory model? It's like a factory that can build cars, airplanes ..., by the external interface, by the customer to decide, to customize which product.
In JS, as a factory function/object, including cars, airplanes and other sub-classes, provide external interface, according to the parameters to return the instances of different subclasses
A simple example is as follows:
varfactory={car:function(name, size) { This. name=name; This. size=size; This. getname=function(){ return This. Name}}, plane:function(name, size) { This. name=name; This. size=size; This. getname=function(){ return This. Name}}, Makecar:function(name, size) {return New This. Car (name, size)}, Makeplane:function(name, size) {return New This. Plane (name, size)}, make:function(type, name, size) {return New This[Type] (name, size)}}varo= factory.make (' Plane ', ' Boeing ', 1000) Console.log (O.getname ())
When to use:
1. Object building is complex
2. Need to rely on a specific environment to create different instances
3. Handling large numbers of small objects with the same attributes
Advantages:
Eliminate coupling between objects, place all instantiated code in one place to avoid code duplication
Disadvantages:
Most classes are best used with the new keyword and constructor to make the code easier and easier to read. Without having to look at the factory method to know
JS Factory Model Brief Introduction