简单工厂模式

概述

简单工厂模式(Simple Factory Pattern)是最简单的工厂模式,也称为静态工厂方法模式。它定义一个工厂类,根据传入的参数不同创建不同的产品实例。

UML类图

text

┌─────────────────┐        ┌─────────────────┐
│    Product      │        │   SimpleFactory │
├─────────────────┤        ├─────────────────┤
│+use(): void     │        │+createProduct() │
└─────────────────┘        └─────────────────┘
         ^                           │
         |                           |
         |                           |
┌─────────────────┐        ┌─────────────────┐
│ ConcreteProductA│        │    Client       │
├─────────────────┤        ├─────────────────┤
│+use(): void     │        │                 │
└─────────────────┘        └─────────────────┘

┌─────────────────┐
│ ConcreteProductB│
├─────────────────┤
│+use(): void     │
└─────────────────┘
#include <iostream>
#include <string>
#include <memory>

// 抽象产品类
class Shape {
public:
    virtual void draw() const = 0;
    virtual ~Shape() = default;
};

// 具体产品类:圆形
class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a Circle" << std::endl;
    }
};

// 具体产品类:矩形
class Rectangle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a Rectangle" << std::endl;
    }
};

// 具体产品类:三角形
class Triangle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a Triangle" << std::endl;
    }
};

// 简单工厂类
class ShapeFactory {
public:
    // 静态工厂方法,根据类型创建不同的形状
    static std::unique_ptr<Shape> createShape(const std::string& type) {
        if (type == "circle") {
            return std::make_unique<Circle>();
        } else if (type == "rectangle") {
            return std::make_unique<Rectangle>();
        } else if (type == "triangle") {
            return std::make_unique<Triangle>();
        } else {
            throw std::invalid_argument("Unknown shape type: " + type);
        }
    }
    
    // 使用枚举类型更安全
    enum class ShapeType { CIRCLE, RECTANGLE, TRIANGLE };
    
    static std::unique_ptr<Shape> createShape(ShapeType type) {
        switch (type) {
            case ShapeType::CIRCLE:
                return std::make_unique<Circle>();
            case ShapeType::RECTANGLE:
                return std::make_unique<Rectangle>();
            case ShapeType::TRIANGLE:
                return std::make_unique<Triangle>();
            default:
                throw std::invalid_argument("Unknown shape type");
        }
    }
};

// 客户端代码
int main() {
    // 使用字符串类型创建
    try {
        auto circle = ShapeFactory::createShape("circle");
        circle->draw();  // 输出: Drawing a Circle
        
        auto rectangle = ShapeFactory::createShape("rectangle");
        rectangle->draw();  // 输出: Drawing a Rectangle
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    
    // 使用枚举类型创建(更安全)
    auto triangle = ShapeFactory::createShape(ShapeFactory::ShapeType::TRIANGLE);
    triangle->draw();  // 输出: Drawing a Triangle
    
    return 0;
}

使用场景

  1. 配置文件解析器:根据文件扩展名创建不同的解析器(XML、JSON、YAML等)

  2. 日志系统:根据配置创建不同的日志输出器(文件、控制台、网络)

  3. 数据库连接:根据数据库类型创建不同的连接对象

  4. 支付系统:根据支付方式创建不同的支付处理器

优点

  1. 封装创建逻辑:客户端无需知道具体产品的创建细节

  2. 职责分离:将对象的创建和使用分离

  3. 减少重复代码:集中管理对象的创建逻辑

缺点/局限性

  1. 违反开闭原则:添加新产品需要修改工厂类

  2. 工厂类职责过重:所有产品创建逻辑集中在一个类中

  3. 不易扩展:当产品种类很多时,工厂类会变得臃肿

  4. 静态方法问题:无法通过继承改变创建行为

适用条件

  • 产品少种类较且相对固定

  • 客户端不关心具体产品的创建过程

  • 不需要频繁添加新产品

工厂方法模式

概述

工厂方法模式(Factory Method Pattern)定义了一个创建对象的接口,但让子类决定实例化哪个类。工厂方法让类的实例化推迟到子类。

UML类图

text

┌─────────────────┐        ┌─────────────────┐
│    Product      │        │    Creator      │
├─────────────────┤        ├─────────────────┤
│+use(): void     │        │+factoryMethod() │
└─────────────────┘        │+anOperation()   │
         ^                 └─────────────────┘
         |                           ^
         |                           |
         |                           |
┌─────────────────┐        ┌─────────────────┐
│ ConcreteProduct │        │ ConcreteCreator │
├─────────────────┤        ├─────────────────┤
│+use(): void     │        │+factoryMethod() │
└─────────────────┘        └─────────────────┘
#include <iostream>
#include <memory>
#include <string>

// 抽象产品:文档
class Document {
public:
    virtual void open() = 0;
    virtual void save() = 0;
    virtual void close() = 0;
    virtual ~Document() = default;
    
    // 模板方法模式结合使用
    void process() {
        open();
        // 这里可以添加一些通用处理逻辑
        save();
        close();
    }
};

// 具体产品:Word文档
class WordDocument : public Document {
public:
    void open() override {
        std::cout << "Opening Word document" << std::endl;
    }
    
    void save() override {
        std::cout << "Saving Word document as .docx" << std::endl;
    }
    
    void close() override {
        std::cout << "Closing Word document" << std::endl;
    }
};

// 具体产品:Excel文档
class ExcelDocument : public Document {
public:
    void open() override {
        std::cout << "Opening Excel spreadsheet" << std::endl;
    }
    
    void save() override {
        std::cout << "Saving Excel spreadsheet as .xlsx" << std::endl;
    }
    
    void close() override {
        std::cout << "Closing Excel spreadsheet" << std::endl;
    }
};

// 具体产品:PDF文档
class PdfDocument : public Document {
public:
    void open() override {
        std::cout << "Opening PDF document" << std::endl;
    }
    
    void save() override {
        std::cout << "Saving PDF document as .pdf" << std::endl;
    }
    
    void close() override {
        std::cout << "Closing PDF document" << std::endl;
    }
};

// 抽象创建者
class Application {
public:
    // 工厂方法:创建文档
    virtual std::unique_ptr<Document> createDocument() = 0;
    
    // 业务逻辑:使用文档
    void newDocument() {
        std::cout << "Creating new document..." << std::endl;
        auto doc = createDocument();
        doc->open();
        // 可以对文档进行一些操作
        doc->save();
        doc->close();
    }
    
    virtual ~Application() = default;
};

// 具体创建者:Word应用
class WordApplication : public Application {
public:
    std::unique_ptr<Document> createDocument() override {
        return std::make_unique<WordDocument>();
    }
};

// 具体创建者:Excel应用
class ExcelApplication : public Application {
public:
    std::unique_ptr<Document> createDocument() override {
        return std::make_unique<ExcelDocument>();
    }
};

// 具体创建者:PDF应用
class PdfApplication : public Application {
public:
    std::unique_ptr<Document> createDocument() override {
        return std::make_unique<PdfDocument>();
    }
};

// 客户端代码
int main() {
    // 使用Word应用
    std::cout << "=== Using Word Application ===" << std::endl;
    std::unique_ptr<Application> wordApp = std::make_unique<WordApplication>();
    wordApp->newDocument();
    
    // 使用Excel应用
    std::cout << "\n=== Using Excel Application ===" << std::endl;
    std::unique_ptr<Application> excelApp = std::make_unique<ExcelApplication>();
    excelApp->newDocument();
    
    // 使用PDF应用
    std::cout << "\n=== Using PDF Application ===" << std::endl;
    std::unique_ptr<Application> pdfApp = std::make_unique<PdfApplication>();
    pdfApp->newDocument();
    
    return 0;
}

使用场景

  1. 框架设计:框架定义接口,子类实现具体创建逻辑

  2. 插件系统:主程序定义接口,插件提供具体实现

  3. 跨平台应用:不同平台有不同的实现

  4. 测试驱动开发:可以使用工厂方法创建Mock对象

优点

  1. 符合开闭原则:添加新产品只需添加新的工厂类

  2. 单一职责原则:每个工厂类只负责创建一种产品

  3. 可扩展性:易于扩展新的产品系列

  4. 代码解耦:客户端代码与具体产品类解耦

缺点/局限性

  1. 类的数量增加:每个产品都需要对应的工厂类

  2. 代码复杂度增加:需要更多的类和接口

  3. 抽象层次多:理解和使用成本较高

  4. 需要客户端知道具体工厂:客户端需要决定使用哪个工厂

适用条件

  • 无法预知需要创建哪种具体对象

  • 系统需要独立于产品的创建、组合和表示

  • 需要为库或框架提供扩展点

抽象工厂模式

概述

抽象工厂模式(Abstract Factory Pattern)提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

UML类图

text

┌─────────────────┐        ┌─────────────────┐
│ AbstractProductA│        │ AbstractProductB│
├─────────────────┤        ├─────────────────┤
│+useA(): void    │        │+useB(): void    │
└─────────────────┘        └─────────────────┘
         ^                           ^
         |                           |
         |                           |
┌─────────────────┐        ┌─────────────────┐
│ ProductA1       │        │ ProductB1       │
├─────────────────┤        ├─────────────────┤
│+useA(): void    │        │+useB(): void    │
└─────────────────┘        └─────────────────┘

┌─────────────────┐        ┌─────────────────┐
│ ProductA2       │        │ ProductB2       │
├─────────────────┤        ├─────────────────┤
│+useA(): void    │        │+useB(): void    │
└─────────────────┘        └─────────────────┘

         ┌────────────────────────────────────┐
         │         AbstractFactory            │
         ├────────────────────────────────────┤
         │+createProductA(): AbstractProductA │
         │+createProductB(): AbstractProductB │
         └────────────────────────────────────┘
                         ^
                         |
          ┌─────────────────────────────┐
          │                             │
┌─────────────────┐        ┌─────────────────┐
│ ConcreteFactory1│        │ ConcreteFactory2│
├─────────────────┤        ├─────────────────┤
│+createProductA()│        │+createProductA()│
│+createProductB()│        │+createProductB()│
└─────────────────┘        └─────────────────┘
#include <iostream>
#include <memory>
#include <string>

// 抽象产品:椅子
class Chair {
public:
    virtual void sitOn() const = 0;
    virtual bool hasLegs() const = 0;
    virtual ~Chair() = default;
};

// 抽象产品:沙发
class Sofa {
public:
    virtual void lieOn() const = 0;
    virtual int getSeats() const = 0;
    virtual ~Sofa() = default;
};

// 抽象产品:咖啡桌
class CoffeeTable {
public:
    virtual void putCoffee() const = 0;
    virtual bool hasStorage() const = 0;
    virtual ~CoffeeTable() = default;
};

// 维多利亚风格产品系列
class VictorianChair : public Chair {
public:
    void sitOn() const override {
        std::cout << "Sitting on a Victorian chair with ornate carvings" << std::endl;
    }
    
    bool hasLegs() const override { return true; }
};

class VictorianSofa : public Sofa {
public:
    void lieOn() const override {
        std::cout << "Lying on a Victorian sofa with velvet upholstery" << std::endl;
    }
    
    int getSeats() const override { return 3; }
};

class VictorianCoffeeTable : public CoffeeTable {
public:
    void putCoffee() const override {
        std::cout << "Putting coffee on a Victorian coffee table with marble top" << std::endl;
    }
    
    bool hasStorage() const override { return true; }
};

// 现代风格产品系列
class ModernChair : public Chair {
public:
    void sitOn() const override {
        std::cout << "Sitting on a Modern chair with minimalist design" << std::endl;
    }
    
    bool hasLegs() const override { return false; }  // 悬浮设计
};

class ModernSofa : public Sofa {
public:
    void lieOn() const override {
        std::cout << "Lying on a Modern sofa with leather upholstery" << std::endl;
    }
    
    int getSeats() const override { return 2; }
};

class ModernCoffeeTable : public CoffeeTable {
public:
    void putCoffee() const override {
        std::cout << "Putting coffee on a Modern coffee table with glass top" << std::endl;
    }
    
    bool hasStorage() const override { return false; }
};

// 抽象工厂接口
class FurnitureFactory {
public:
    virtual std::unique_ptr<Chair> createChair() const = 0;
    virtual std::unique_ptr<Sofa> createSofa() const = 0;
    virtual std::unique_ptr<CoffeeTable> createCoffeeTable() const = 0;
    virtual ~FurnitureFactory() = default;
    
    // 可以创建配套的家具组合
    void createFurnitureSet() const {
        auto chair = createChair();
        auto sofa = createSofa();
        auto table = createCoffeeTable();
        
        std::cout << "\nCreating furniture set:" << std::endl;
        chair->sitOn();
        sofa->lieOn();
        table->putCoffee();
    }
};

// 具体工厂:维多利亚风格工厂
class VictorianFurnitureFactory : public FurnitureFactory {
public:
    std::unique_ptr<Chair> createChair() const override {
        return std::make_unique<VictorianChair>();
    }
    
    std::unique_ptr<Sofa> createSofa() const override {
        return std::make_unique<VictorianSofa>();
    }
    
    std::unique_ptr<CoffeeTable> createCoffeeTable() const override {
        return std::make_unique<VictorianCoffeeTable>();
    }
};

// 具体工厂:现代风格工厂
class ModernFurnitureFactory : public FurnitureFactory {
public:
    std::unique_ptr<Chair> createChair() const override {
        return std::make_unique<ModernChair>();
    }
    
    std::unique_ptr<Sofa> createSofa() const override {
        return std::make_unique<ModernSofa>();
    }
    
    std::unique_ptr<CoffeeTable> createCoffeeTable() const override {
        return std::make_unique<ModernCoffeeTable>();
    }
};

// 客户端代码
class FurnitureStore {
private:
    std::unique_ptr<FurnitureFactory> factory_;
    
public:
    FurnitureStore(std::unique_ptr<FurnitureFactory> factory)
        : factory_(std::move(factory)) {}
    
    void setFactory(std::unique_ptr<FurnitureFactory> factory) {
        factory_ = std::move(factory);
    }
    
    void displayCatalog() const {
        if (!factory_) {
            std::cout << "No factory set!" << std::endl;
            return;
        }
        
        std::cout << "\n=== Furniture Catalog ===" << std::endl;
        
        std::cout << "Chair: ";
        auto chair = factory_->createChair();
        chair->sitOn();
        std::cout << "Has legs: " << (chair->hasLegs() ? "Yes" : "No") << std::endl;
        
        std::cout << "Sofa: ";
        auto sofa = factory_->createSofa();
        sofa->lieOn();
        std::cout << "Seats: " << sofa->getSeats() << std::endl;
        
        std::cout << "Coffee Table: ";
        auto table = factory_->createCoffeeTable();
        table->putCoffee();
        std::cout << "Has storage: " << (table->hasStorage() ? "Yes" : "No") << std::endl;
    }
    
    void orderFurnitureSet() const {
        if (factory_) {
            factory_->createFurnitureSet();
        }
    }
};

int main() {
    // 创建维多利亚风格家具店
    std::cout << "=== Victorian Furniture Store ===" << std::endl;
    auto victorianFactory = std::make_unique<VictorianFurnitureFactory>();
    FurnitureStore victorianStore(std::move(victorianFactory));
    victorianStore.displayCatalog();
    victorianStore.orderFurnitureSet();
    
    // 切换到现代风格家具店
    std::cout << "\n=== Modern Furniture Store ===" << std::endl;
    auto modernFactory = std::make_unique<ModernFurnitureFactory>();
    FurnitureStore modernStore(std::move(modernFactory));
    modernStore.displayCatalog();
    modernStore.orderFurnitureSet();
    
    return 0;
}

使用场景

  1. 跨平台UI框架:为不同操作系统创建一套UI组件

  2. 数据库抽象层:支持多种数据库,保持接口统一

  3. 游戏开发:为不同风格的游戏创建角色、武器、场景等

  4. 电商系统:根据不同地区创建不同的支付、物流、税收策略

  5. 报告生成系统:支持多种格式(PDF、Excel、HTML)和多种样式

优点

  1. 产品系列一致性:确保创建的产品相互兼容

  2. 客户端与具体类解耦:客户端只依赖抽象接口

  3. 易于交换产品系列:只需更换具体工厂

  4. 符合开闭原则:添加新产品系列容易

缺点/局限性

  1. 难以支持新种类的产品:添加新产品需要修改抽象工厂接口

  2. 代码复杂度高:需要大量的类和接口

  3. 学习曲线陡峭:理解和实现都需要较高成本

  4. 过度设计风险:对于简单系统可能是过度设计

适用条件

  • 系统需要独立于产品的创建、组合和表示

  • 系统需要配置多个产品系列中的一个

  • 需要强调一系列相关产品的联合使用

  • 产品库需要只暴露接口,隐藏实现

三种工厂模式对比

特性简单工厂模式工厂方法模式抽象工厂模式
复杂度低中高
灵活性低中高
扩展性差(需修改代码)好(添加新产品)好(添加新系列)
产品关系独立产品独立产品相关产品族
开闭原则违反符合部分符合
适用场景产品种类少且固定产品种类可能扩展需要产品系列一致性

选择建议

  1. 简单工厂模式:

    • 产品类型固定,不会频繁增加

    • 创建逻辑简单

    • 不需要复杂的扩展性

  2. 工厂方法模式:

    • 无法预知需要创建的具体类型

    • 需要为框架提供扩展点

    • 各个产品的创建逻辑相对独立

  3. 抽象工厂模式:

    • 需要创建相互关联或依赖的产品系列

    • 系统需要独立于产品的创建和组合

    • 需要强调产品的一致性

最佳实践

  1. 结合使用:在实际项目中,可以结合使用多种工厂模式

  2. 参数化工厂:使用配置或参数决定使用哪个具体工厂

  3. 延迟初始化:在工厂中实现对象的缓存和复用

  4. 错误处理:在工厂方法中添加适当的异常处理

  5. 依赖注入:使用工厂模式配合依赖注入容器

工厂模式是面向对象设计中最重要的模式之一,理解并正确使用工厂模式可以大大提升代码的灵活性、可维护性和可测试性。在实际开发中,应根据具体需求选择合适的工厂模式,避免过度设计。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐