上一篇:1. 工厂方法模式(Factory Method Pattern)
抽象工厂模式(Abstract Factory Pattern)是一种创建型设计模式,它提供了一个接口,用于创建一组相关或相互依赖的对象,而不需要指定它们的具体类。
下面是使用 TypeScript 实现抽象工厂模式的例子:
interface Shape {
draw(): void;
}
class Rectangle implements Shape {
draw(): void {
console.log('Inside Rectangle::draw() method.');
}
}
class Square implements Shape {
draw(): void {
console.log('Inside Square::draw() method.');
}
}
class Circle implements Shape {
draw(): void {
console.log('Inside Circle::draw() method.');
}
}
interface Color {
fill(): void;
}
class Red implements Color {
fill(): void {
console.log('Inside Red::fill() method.');
}
}
class Green implements Color {
fill(): void {
console.log('Inside Green::fill() method.');
}
}
class Blue implements Color {
fill(): void {
console.log('Inside Blue::fill() method.');
}
}
interface AbstractFactory {
createShape(): Shape;
createColor(): Color;
}
class ShapeFactory implements AbstractFactory {
createShape(): Shape {
return new Rectangle();
}
createColor(): Color {
return new Red();
}
}
class ColorFactory implements AbstractFactory {
createShape(): Shape {
return new Circle();
}
createColor(): Color {
return new Green();
}
}
class FactoryProducer {
static getFactory(choice: 'shape' | 'color'): AbstractFactory {
if (choice === 'shape') {
return new ShapeFactory();
} else if (choice === 'color') {
return new ColorFactory();
}
return null;
}
}
// 使用示例
const shapeFactory = FactoryProducer.getFactory('shape');
const shape = shapeFactory.createShape();
shape.draw();
const colorFactory = FactoryProducer.getFactory('color');
const color = colorFactory.createColor();
color.fill();
在上面的例子中,我们定义了两个产品族:Shape
和 Color
。Shape
有三个具体实现类:Rectangle
、Square
和 Circle
;Color
也有三个具体实现类:Red
、Green
和 Blue
。我们定义了一个抽象工厂 AbstractFactory
,它有两个工厂方法 createShape
和 createColor
,用于创建产品族中的对象。然后我们又定义了两个具体的工厂 ShapeFactory
和 ColorFactory
,它们分别实现了 AbstractFactory
接口,用于创建具体的产品族。最后我们定义了一个 FactoryProducer
工厂生产器,根据用户的选择返回不同的工厂对象。
在使用时,我们只需要通过 FactoryProducer
获取到相应的工厂对象,然后使用工厂对象创建产品即可。