创造者模式

77 阅读1分钟

工厂模式创建出一个对象,它追求的创建结果

创建者模式参与了创建过程,对于创建的具体实现的细节参与了干涉

const Human = function (params) {
  this.skill = (params && params.skill) || "保密";
  this.hobby = (params && params.hobby) || "保密";
};
Human.prototype = {
  getKill: function () {
    return this.skill;
  },
  getHobby: function () {
    return this.hobby;
  },
};
const Named = function (name) {
  let that = this;
  (function (name, that) {
    that.whloeName = name;
    // that.name = name;
  })(name, that);
};
const Work = function (work) {
  let that = this;
  (function (work, that) {
    switch (work) {
      case "code":
        that.work = "开发工程师";
        break;
      case "teacher":
        that.work = "人民教师";
        break;
    }
  })(work, that);
};
Work.prototype.changeWork = function (work) {
  this.work = work;
};

// 创建者
const Person = function (name, work) {
  let _person = new Human();
  _person.name = new Named(name);
  _person.work = new Work(work);
  return _person;
};

const person = new Person("xiao ming", "code");

console.log(person.name);
console.log(person.name.whloeName);
console.log(person.work.work);
console.log(person.getKill());

// Named { whloeName: 'xiao ming' }
// xiao ming
// 开发工程师
// 保密