- 将new操作单独封装
- 遇到new的时候,就需要考虑是否该用到工厂模式
class Product {constructor(name) {this.name = name}init() {}func1() {}func2() {}}class Creator {create(name) {return new Product()}}let creator = new Creator()let p = creator.create('p1') // 工厂方式实例化类p.init()p.func1()
UML类图:
举例:
- jQuery
window.$ = function(selector) { // $就是一个工厂,返回实例化后的jQueryreturn new jQuery(selector)}
- React.createElement()
class Vnode(tag, props, children) {/* 省略部分代码 */}// jsx其实就是createElement的语法糖React.createElement = function(tag, props, children) {/* 省略部分代码 */return new Vnode(tag, props, children)}
验证:
- 构造函数和创建者是分离的
- 符合开放封闭原则
