Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

The Factory Method pattern (Factory Method), also known as the polymorphic Factory pattern, is no longer responsible for the creation of all the subclasses like the simple Factory pattern, but leaves the specific creation work to the subclasses

When we introduced the simple factory pattern, we wrote the following code:

/** * type: role type - Administrator and employee * name: role name */
const Factory = (type, name) = > {
  switch (type) {
    case "admin": // Create an administrator
      return new Admin(name, ["user"."salary"."vacation"]);
    case "staff": // Create an employee
      return new Staff(name, ["vacation"]);
    default: // Robust processing
      throw new Error("Creation of this role is not currently supported"); }};Copy the code

While it can be fun to create an instance without worrying about the internal implementation, it can be problematic to look at the code:

  • Not in accordance with the design principle – open and closed principle

Every time a new permission role is added, the above code needs to be modified, which seriously damages the original code and business logic, and deviates from the open and closed principle

  • Easy to turn into noodle code

As the number of roles increases, so does the number of internal cases, and the content of simple factory functions becomes redundant

Ideally, we want to be able to add functionality without making any changes to the old code when adding a new permission role

First, take a look at UML for the factory method pattern:

Instead of simple factory mode, there will be one more factory method, the Admin class corresponds to an AdminFactory class, now you only need to create instances through the AdminFactory class

Let’s look at how the factory method pattern is created:

class Person {
    constructor(name, permission) {
        this.name = name;
        this.permission = permission; }}/**
 * 管理员
 */
class Admin extends Person {
    constructor(name, permission) {
        super(name, permission); }}/** * Administrator's factory method */
class AdminFactory {
    static create(name) {
        return new Admin(name, ["user"."salary"."vacation"]); }}/** * employee */
class Staff extends Person {
    constructor(name, permission) {
        super(name, permission); }}/** ** Factory method for employees */
class StaffFactory {
    static create(name) {
        return new Staff(name, ["vacation"]); }}const admin = AdminFactory.create("Administrator");
const zs = StaffFactory.create("Zhang");
const ls = StaffFactory.create("Bill");
Copy the code

If you need to create a new permission role, you only need to create the corresponding factory method, in full compliance with the open and closed principle, can also avoid the noodle code, specific instances are created through the corresponding factory method