#简单工厂

#构造器

写变量对象时,字面量需要一个个定义,每次都要写很麻烦

const liLei = {
  name: '李雷',
  age: 25,
  career: 'coder',
}
const wangBa = {
  name: '王八',
  age: 29,
  career: 'product manager',
}

通过构造器批量构造

function User(name, age, career) {
  this.name = name
  this.age = age
  this.career = career
}

这样就讲变与不变分离,变的是值,不变的是属性,每次只需要传入新的值即可

#简单工厂模式

那如果人的 work 会根据 career 变化,构造器就不够了,需要通过 if 逻辑来赋值

这时候需要工厂

function Coder(name, age) {
  this.name = name
  this.age = age
  this.career = 'coder'
  this.work = ['写代码', '写系分', '修Bug']
}
function ProductManager(name, age) {
  this.name = name
  this.age = age
  this.career = 'product manager'
  this.work = ['订会议室', '写PRD', '催更']
}

工厂可以封装逻辑,将处理后的值传入构造器

function User(name , age, career, work) {
    this.name = name
    this.age = age
    this.career = career
    this.work = work
}

function Factory(name, age, career) {
    let work
    switch(career) {
        case 'coder':
            work =  ['写代码','写系分', '修Bug']
            break
        case 'product manager':
            work = ['订会议室', '写PRD', '催更']
            break
        case 'boss':
            work = ['喝茶', '看报', '见客户']
        case 'xxx':
            // 其它工种的职责分配
            ...

    return new User(name, age, career, work)
}

工厂封装了构造的逻辑

#小结

构造器是将创建对象的过程单独封装,解决的是创建多个对象实例的问题 简单工厂是将创建类的过程单独封装,解决的是创建多个类的问题