本文共 1707 字,大约阅读时间需要 5 分钟。
简单工厂模式(Simple Factory Pattern),也称为静态工厂方法模式。它通过一个工厂对象来创建特定类型的对象。这种设计模式属于创建型模式(Creational Pattern)。简单工厂模式的核心思想是:根据不同的参数,返回不同的实例类。被创建的对象通常具有共同的父类,从而使得工厂模式能够集中管理对象的创建逻辑。
简单工厂模式的主要目标是定义一个创建对象的接口,让子类决定使用哪一个工厂来创建实例。工厂方法将创建过程推迟到工厂方法中执行,解决接口选择问题。通过这种方式,子类可以实现工厂接口,并返回抽象的产品。
简单工厂模式的结构包括以下几个角色:
以下是一个简单工厂模式的实现示例:
class Shape { say() { console.log(this.name); }}class Rectangle extends Shape { constructor() { super(); this.name = "Rectangle"; }}class Square extends Shape { constructor() { super(); this.name = "Square"; }}class Circle extends Shape { constructor() { super(); this.name = "Circle"; }}class ShapeFactory { getShape(shape) { switch (shape.toLowerCase()) { case "rectangle": return new Rectangle(); case "square": return new Square(); case "circle": return new Circle(); default: throw new Error("参数错误"); } }}const shapeFactory = new ShapeFactory();const rectangle = shapeFactory.getShape("rectangle");rectangle.say(); // 输出: Rectangleconst square = shapeFactory.getShape("square");square.say(); // 输出: Squareconst circle = shapeFactory.getShape("circle");circle.say(); // 输出: Circle 转载地址:http://btckz.baihongyu.com/