1. 程式人生 > 其它 >js的工廠模式

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();