js的工厂模式

js的工厂模式旨在于能够新建一个工厂,从工厂中生产出所需要的类,可以解决一些复杂场景:

class person {
  constructor(name) {
    this.type = "人";
    this.name = name;
  }
}

class man extends person {
  constructor(name) {
    super(name);
    this.sex = "男";
  }
}
class woman extends person {
  constructor(name) {
    super(name);
    this.sex = "女";
  }
}

// 工厂类
function Factory() { // 设计一个存储对象各种对象的数据 this.empDict = {}; this.addEmpObj = function (key, obj) { if (!this.empDict[key]) this.empDict[key] = obj; }; this.createEmp = function () { var key = Array.prototype.shift.call(arguments); if (!key || !this.empDict[key]) throw new Error("没有找到指定对象"); let n_obj = new this.empDict[key](...arguments); // 用工厂类给对象赋予一个公共的方法 n_obj.say = function () { console.log("我的名字是:", this.name,"--我们的口号是:今天睡地板,明天当老板!"); }; return n_obj; }; } let fa = new Factory(); fa.addEmpObj("man", man);// 将男人类放到工厂中 fa.addEmpObj("woman", woman);// 将女人类放到工厂中 let cc = fa.createEmp("man", "xcc"); cc.say(); let jh = fa.createEmp("woman", "djh"); jh.say();

 

posted @ 2022-03-11 11:40  xiaochuchun  阅读(60)  评论(0编辑  收藏  举报