工厂模式(Factory Pattern),根据不同的名称输入返回不同类的实例,一般用来创建同一类对象。工厂模式的主要思想是将对象的创建与对象的实现分离。
在类似场景中,这些例子有以下特点:
工厂模式分为简单工厂模式、工厂方法模式、抽象工厂模式。
简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例
简单工厂模式包含如下角色:
类图: AmericanoCoffee、LatteCoffee和CappuccinoCoffee都是继承Coffee
代码
abstract class Coffee {
constructor(public name: string) {
}
}
class AmericanoCoffee extends Coffee {
constructor(public name: string) {
super(name);
}
}
class LatteCoffee extends Coffee {
constructor(public name: string) {
super(name);
}
}
class CappuccinoCoffee extends Coffee {
constructor(public name: string) {
super(name);
}
}
class Café {
static order(name: string) {
switch (name) {
case 'Americano':
return new AmericanoCoffee('美式咖啡');
case 'Latte':
return new LatteCoffee('拿铁咖啡');
case 'Cappuccino':
return new LatteCoffee('卡布奇诺');
default:
return null;
}
}
}
console.log(Café.order('Americano'));
console.log(Café.order('Latte'));
console.log(Café.order('Cappuccino'));
jQuery
class jQuery{
constructor(selector){
let elements = Array.from(document.querySelectorAll(selector));
let length = elements?elements.length:0;
for(let i=0;i
和原生的 document.createElement 类似,Vue 和 React 这种具有虚拟 DOM 树(Virtual Dom Tree)机制的框架在生成虚拟 DOM 的时候,都提供了 createElement 方法用来生成 VNode,用来作为真实 DOM 节点的映射
// Vue
createElement('h3', { class: 'main-title' }, [
createElement('img', { class: 'avatar', attrs: { src: '../avatar.jpg' } }),
createElement('p', { class: 'user-desc' }, '放弃不难,但坚持一定很酷')
])
// React
React.createElement('h3', { className: 'user-info' },
React.createElement('img', { src: '../avatar.jpg', className: 'avatar' }),
React.createElement('p', { className: 'user-desc' }, '放弃不难,但坚持一定很酷')
)
createElement 函数结构大概如下:
class Vnode (tag, data, children) { ... }
function createElement(tag, data, children) {
return new Vnode(tag, data, children)
}
可以看到 createElement 函数内会进行 VNode 的具体创建,创建的过程是很复杂的,而框架提供的 createElement 工厂方法封装了复杂的创建与验证过程,对于使用者来说就很方便了。
工厂模式在源码中应用频繁,以 vue-router 中的源码为例,代码位置:vue-router/src/index.js
// src/index.js
export default class VueRouter {
constructor(options) {
this.mode = mode // 路由模式
switch (mode) { // 简单工厂
case 'history': // history 方式
this.history = new HTML5History(this, options.base)
break
case 'hash': // hash 方式
this.history = new HashHistory(this, options.base, this.fallback)
break
case 'abstract': // abstract 方式
this.history = new AbstractHistory(this, options.base)
break
default:
// ... 初始化失败报错
}
}
}
稍微解释一下这里的源码。mode 是路由创建的模式,这里有三种 History、Hash、Abstract,前两种我们已经很熟悉了,History 是 H5 的路由方式,Hash 是路由中带 # 的路由方式,Abstract 代表非浏览器环境中路由方式,比如 Node、weex 等;this.history 用来保存路由实例,vue-router 中使用了工厂模式的思想来获得响应路由控制类的实例。
源码里没有把工厂方法的产品创建流程封装出来,而是直接将产品实例的创建流程暴露在 VueRouter 的构造函数中,在被 new 的时候创建对应产品实例,相当于 VueRouter的构造函数就是一个工厂方法。
如果一个系统不是 SPA (Single Page Application,单页应用),而是是 MPA(Multi Page Application,多页应用),那么就需要创建多个 VueRouter 的实例,此时 VueRouter 的构造函数也就是工厂方法将会被多次执行,以分别获得不同实例。
简单工厂模式是根据输入的不同返回不同产品的实例;而工厂方式的主要思想是增加抽象工厂类,将不同产品的创建分离到不同的工厂中,工厂类的职责比较单一。
abstract class Coffee {
constructor(public name: string) {
}
}
abstract class Factory {
abstract createCoffee(): Coffee;
}
class AmericanoCoffee extends Coffee {
constructor(public name: string) {
super(name);
}
}
class AmericanoCoffeeFactory extends Factory {
createCoffee() {
return new AmericanoCoffee('美式咖啡')
}
}
class LatteCoffee extends Coffee {
constructor(public name: string) {
super(name);
}
}
class LatteCoffeeFactory extends Factory {
createCoffee() {
return new LatteCoffee('拿铁咖啡')
}
}
class CappuccinoCoffee extends Coffee {
constructor(public name: string) {
super(name);
}
}
class CappuccinoFactory extends Factory {
createCoffee() {
return new CappuccinoCoffee('卡布奇诺')
}
}
class Café {
static order(name: string) {
switch (name) {
case 'Americano':
return new AmericanoCoffeeFactory().createCoffee();
case 'Latte':
return new LatteCoffeeFactory().createCoffee();
case 'Cappuccino':
return new CappuccinoFactory().createCoffee();
default:
return null;
}
}
}
console.log(Café.order('Americano'));
console.log(Café.order('Latte'));
console.log(Café.order('Cappuccino'));
const settings={
'Americano': AmericanoCoffeeFactory,
'Latte': LatteCoffeeFactory,
'Cappuccino': CappuccinoFactory
}
console.log(new settings('Americano').createCoffee());
console.log(new settings('Latte').createCoffee());
console.log(new settings('Cappuccino').createCoffee());
带来了额外的系统复杂度,增加了抽象性。
那在什么时候使用工厂模式呢:
什么时候不该用工厂模式:
滥用只是增加了不必要的系统复杂度,过犹不及。
页面更新:2024-05-04
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号