工厂模式

49 阅读1分钟

简单工厂

  1. 优点

    1. 只需要一个正确的参数,就可以获取到你所需要的对象,而无需知道其创建的具体细节
  2. 不足

    1. 在函数内包含了所有对象的创建逻辑(构造函数)和判断逻辑的代码,每增加新的构造函数还需要修改判断逻辑代码,难以维护
  3. 简单工厂只能作用于创建的对象数量较少,对象的创建逻辑不复杂时使用

  4. demo

class User {
  constructor(opt) {
    this.name = opt.name;
    this.viewPage = opt.viewPage;
  }
  static getInstance(role) {
    switch (role) {
      case "superAdmin":
        return new User({
          name: "超级管理员",
          viewPage: ["首页", "应用数据", "权限管理"],
        });
        break;
      case "admin":
        return new User({
          name: "超级管理员",
          viewPage: ["首页", "应用数据"],
        });
        break;
      case "user":
        return new User({ name: "用户", viewPage: ["首页"] });
    }
  }
}
// 调用
let superAdmin = User.getInstance("superAdmin");
let admin = User.getInstance("admin");
let user = User.getInstance("user");


function createPop(type, text) {
  const o = new Object();
  o.content = text;
  o.show = function () {
    console.log(this.content);
  };

  if (type === "alert") {
    o.ui = function () {
      console.log("element");
    };
  }
  if (type === "prompt") {
    o.ui = function () {
      console.log("iview");
    };
  }
  return o;
}

const userAlert = createPop("prompt", "i am");
userAlert.ui();
userAlert.show();

工厂方法

  1. 定义 通过对产品类的抽象使其创建业务主要负责用于创建多类产品的实例 将实际创建对象工作推迟到子类当中,核心类成了抽象类

创建多类对象,简单工厂就不太合适了,工厂方法正合适。

  1. 安全类
const Factory = function (type, content) {
  if (this instanceof Factory) {
    let s = new this[type](content);
  } else {
    return new Factory(type, content);
  }
};
  1. demo
const Factory = function (type, content) {
  if (this instanceof Factory) {
    let s = new this[type](content);
  } else {
    return new Factory(type, content);
  }
};
Factory.prototype = {
  Java: function (content) {},
  JS: function (content) {},
  UI: function (content) {},
};
const data = [
  { type: "javascript", content: "javascript 哪家强" },
  { type: "java", content: "java 哪家强" },
  { type: "ui", content: "ui 哪家强" },
];
for (let i = 0; i < 3; i++) {
  Factory(data[i].type, data[i].content);
}

抽象工厂