The factory pattern

The factory pattern (simple Factory pattern) defines the interface for creating objects and lets subclasses decide which class to instantiate.

When creating an instance is complex and writing to a constructor makes the constructor code complex and less readable, use a special class (which in Javascript can be simplified to a function) to create the object.

// Create an interface
interface Shape {
  draw: () = > void;
}

enum ShapeType {
  "Rectangle" = 1."Circular"
}

// Create an entity class for the interface implementation
class Rectangle implements Shape {
  draw = () = > {
    console.log("draw Rectangle"); }}class Circle implements Shape {
  draw = () = > {
    console.log("draw Circle"); }}// Create a factory to generate objects of the entity class
const shapeFactory = (type: ShapeType) = > {
  if (type=== ShapeType. Rectangle) {return new Rectangle();
  } else if (type=== ShapeType. Circle) {return new Circle();
  }
  return null
}

// Use this project to get the object of the entity class by passing type information
constshape1 = shapeFactory(ShapeType. Rectangular); shape1.draw();// draw Rectangle

constshape2 = shapeFactory(ShapeType. Circular); shape2.draw();// draw Circle
Copy the code

advantages

  1. All the caller needs to know to create an instance is its name(ShapeType).
  2. To add a new type, you only need to extend a class(Rectangle/Circle/…).
  3. The implementation of concrete classes is shielded, object creation is separated from object usage, and the caller only cares about the interface(shapeFactory).

disadvantages

  1. Each time you add a new type, you need to add a concrete class and the logic in the implementation factory.
  2. The number of classes in the system increases exponentially, which increases the complexity of the system to a certain extent and the dependence of the system on specific classes.