【前端设计模式】工厂模式

127 阅读1分钟

工厂模式的作用

创建对象的方式。 利用“工厂”创建对象,而非手动创建对象。

标准工厂模式

未命名文件(11).png

// 可扩展多个类
interface IPerson {
  name: string
  job: () => void
  work: () => void
}

class Teacher implements IPerson {
  name: string
  constructor(name: string) {
    this.name = name
  }
  job() {
    console.log(`${this.name} is a teacher.`)
  }
  work() {
    console.log(`${this.name} is teaching.`)
  }
}

class Student implements IPerson {
  name: string
  constructor(name: string) {
    this.name = name
  }
  job() {
    console.log(`${this.name} is a student.`)
  }
  work() {
    console.log(`${this.name} is studying.`)
  }
}

class Creator {
  create(type: string, name: string): IPerson {
    switch(type) {
      case 'Teacher':
        return new Teacher(name)
      case 'Student':
        return new Student(name)
      default:
        throw new Error('Invalid Type')
    }
  }
}

// 工厂和类解耦
const factory = new Creator();

const student = factory.create('Student', 'John')
student.job()
student.work()

const teacher = factory.create('Teacher', 'Tom')
teacher.job()
teacher.work()

符合开放封闭原则(对扩展开放,对修改封闭)

工厂模式在Vue中的应用

Vue模板渲染简述

未命名文件(13).png

Vue模板

<div>
  <span>static text</span>
  <span :id="hello" class="bar">{{ msg }}</span>
</div>

虚拟DOM

import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_openBlock(), _createElementBlock("div", null, [
    _createElementVNode("span", null, "static text"),
    _createElementVNode("span", {
      id: _ctx.hello,
      class: "bar"
    }, _toDisplayString(_ctx.msg), 9 /* TEXT, PROPS */, ["id"])
  ]))
}