当前位置:   article > 正文

前端常用的设计模式总结——工厂模式_前端工厂模式

前端工厂模式

工厂模式的直观目的就是减少代码中new出现的次数
工厂工厂,就像是流水线,将材料(参数)放进去,给你返回一个加工好的产品(实例对象)
一般我们会封装一个构造函数,并在其中去return new Fun(),也就是return我们想要的实例对象,这样我们想要去获取某个构造函数的实例,就不需要写那么多new了,而是可以直接调用使用了工厂模式的函数,将参数传进去,就可以获得我们想要的实例

// 简单工厂模式
class Target {
	name: string
	constructor(name: string) {
		this.name = name
	}
	fn() {console.log(this.name)}
}
// 工厂
class Creator {
	create(name: string): Target {
		return new Target(name)
	}
}
const creator = new Creator()
const t1 = creator.create('张三')
const t2 = creator.create('李四')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

简单的工厂模式非常的直观,而标准的工厂模式,会在工厂函数里边添加一些逻辑判断或者业务逻辑

// 标准的工厂模式
type FnType = () => void
interface ITarget {
	name: string
	fn: FnType
}
class Target1 implements ITarget {
	name: string
	constructor(name: string) {
		this.name = name
	}
	fn() {console.log(this.name)}
}
class Target2 implements ITarget {
	name: string
	constructor(name: string) {
		this.name = name
	}
	fn() {console.log(this.name)}
}
// 工厂
class Creator {
	create(type: string, name: string): ITarget {
		if (type === 'A') {
			return new Target1(name)
		}
		if (type === 'B') {
			return new Target2(name)
		}
		throw new Error('Invalid type')
	}
}
const creator = new Creator()
const t1 = creator.create('A', '张三')
const t2 = creator.create('B', '李四')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/844909
推荐阅读
相关标签
  

闽ICP备14008679号