Day03-工厂模式

117 阅读1分钟

先来看一段示例:

  • 需求:
    1. 后台传来 类型字段 type ,我们需要根据 type 字段来展示对应的中文
    2. 同时需要保存 后台本来的数据,方便修改和使用

工厂函数实现

  • formattingType 函数就是简单的 工厂函数,
  • 工厂函数可以理解为,一个 hooks,
  • 或者说理解为一个 "真正的工厂",可以在这个工厂中把你的数据进行加工,然后返回你需要的产品
    function typeOptions(type, typeStr) {
      this.type = type;
      this.typeStr = typeStr;
    }
    function formattingType(type) {
      switch (type) {
        case 1:
          return new typeOptions("1", "正则判断");
        case 2:
          return new typeOptions("2", "长度判断");
        case 3:
          return new typeOptions("3", "boolean 判断");
        default:
          return "暂无格式数据";
      }
    }

    console.log(formattingType()); // 暂无格式数据
    console.log(formattingType(1)); // { type: '1', typeStr: '正则判断' }
    console.log(formattingType(2)); // { type: '2', typeStr: '长度判断' }
    console.log(formattingType(3)); // { type: '3', typeStr: 'boolean 判断' }

在 ES6 class 实现

  • 知识点: class 中的 静态属性-static 俩个特性
  • 1. 不需要实例化即可调用的属性。
  • 2. 实例化之后不可调用
    class formattingType2 {
      constructor(type, typeStr) {
        this.type = type;
        this.typeStr = typeStr;
      }
      static formtT(type) {
        switch (type) {
          case 1:
            return new formattingType2("1", "正则判断");
          case 2:
            return new formattingType2("2", "长度判断");
          case 3:
            return new formattingType2("3", "boolean 判断");
          default:
            return "暂无格式数据";
        }
      }
    }
    console.log(formattingType2.formtT(1)); // { type: '1', typeStr: '正则判断' }
    console.log(formattingType2.formtT(2)); // { type: '2', typeStr: '长度判断' }
    console.log(formattingType2.formtT(3)); // { type: '3', typeStr: 'boolean 判断' }
    console.log(new formattingType2(1).formtT); // undefined