工厂模式(Factory Pattern
)是一种创建型设计模式,它提供了一种创建对象的接口,但将对象的实际创建细节延迟到了子类或具体实现类。工厂模式主要用于创建对象,而不是通过直接调用构造函数来实例化对象。这样可以解耦对象的创建过程,使得代码更加灵活、可维护和可扩展。
你没注意到的工厂模式
-
Vue Router
中的工厂模式 点击查看 -
React
中的工厂模式 点击查看 -
还有就是最常见的
document.createElement
const div = document.createElement('div') const p = document.createElement('p') console.log(div.__proto__.constructor) // ƒ HTMLDivElement() { [native code] } console.log(p.__proto__.constructor) // ƒ HTMLParagraphElement() { [native code] }
通用实现
// 定义产品接口
interface Product {
name: string
price: number
}
// 定义产品类型
type ProductType = 'A' | 'B' // 假设有两种类型的产品
// 具体产品实现类
class ConcreteProductA implements Product {
name: string
price: number
constructor() {
this.name = 'Product A'
this.price = 100
}
}
class ConcreteProductB implements Product {
name: string
price: number
constructor() {
this.name = 'Product B'
this.price = 200
}
}
// 工厂类
class ProductFactory {
createProduct(type: ProductType): Product {
switch (type) {
case 'A':
return new ConcreteProductA()
case 'B':
return new ConcreteProductB()
default:
throw new Error('Invalid product type.')
}
}
}
// 示例用法
const factory = new ProductFactory()
const productA = factory.createProduct('A')
const productB = factory.createProduct('B')
console.log(productA) // Output: ConcreteProductA { name: 'Product A', price: 100 }
console.log(productB) // Output: ConcreteProductB { name: 'Product B', price: 200 }