工厂模式
工厂模式(简单工厂模式)定义创建对象的接口,让子类决定实例化哪个类。
当创建一个实例很复杂时,如果这些操作写到构造函数里会使构造函数的代码很复杂,降低了代码的可读性,这个时候使用一个特殊的类(Javascript 中可以简化为函数)去负责对象的创建工作。
// 创建一个接口
interface Shape {
draw: () => void;
}
enum ShapeType {
"长方形" = 1,
"圆形"
}
// 创建接口实现的实体类
class Rectangle implements Shape {
draw = () => {
console.log("draw Rectangle");
}
}
class Circle implements Shape {
draw = () => {
console.log("draw Circle");
}
}
// 创建一个工厂,生成实体类的对象
const shapeFactory = (type: ShapeType) => {
if (type === ShapeType.长方形) {
return new Rectangle();
} else if (type === ShapeType.圆形) {
return new Circle();
}
return null
}
// 使用该工程,通过传递类型信息获取实体类的对象
const shape1 = shapeFactory(ShapeType.长方形);
shape1.draw(); // draw Rectangle
const shape2 = shapeFactory(ShapeType.圆形);
shape2.draw(); // draw Circle
优点
- 调用者想创建一个实例只需要知道其名称就可以了 (ShapeType)。
- 扩展性高,想要增加一个新的类型,只要扩展一个类即可 (Rectangle/Circle/...)。
- 屏蔽具体类的实现,对象的创建和对象的使用分离,调用者只关心接口 (shapeFactory)。
缺点
- 每次增加一个新的类型时,都需要增加一个具体类和实现工厂中的逻辑。
- 系统中类的个数成倍增加,一定程度上增加了系统的复杂度,和系统对具体类的依赖。