23种设计模式 - 工厂方法模式

模式定义

工厂方法模式(Factory Method Pattern)是一种创建型设计模式,定义用于创建对象的接口,让子类决定实例化哪个类,从而将对象创建过程延迟到子类。其核心目的是解耦对象的创建与使用,增强系统的扩展性,符合开闭原则。


模式结构

抽象产品(Product):定义对象的接口(如数控系统中的运动控制器)。

具体产品(Concrete Product):实现抽象产品的具体类(如直线运动、圆弧运动控制器)。

抽象工厂(Creator):声明工厂方法,返回抽象产品类型。

具体工厂(Concrete Creator):重写工厂方法,返回具体产品实例。


C++示例(数控系统场景)

cpp 复制代码
#include 

// 抽象产品:运动控制器接口
class MotionController {
public:
    virtual void execute() = 0;
    virtual ~MotionController() = default;
};

// 具体产品1:直线运动控制器
class LinearMotion : public MotionController {
public:
    void execute() override {
        std::cout << "执行直线插补运动" << std::endl;
    }
};

// 具体产品2:圆弧运动控制器
class ArcMotion : public MotionController {
public:
    void execute() override {
        std::cout << "执行圆弧插补运动" << std::endl;
    }
};

// 抽象工厂
class MotionFactory {
public:
    virtual MotionController* createMotion() = 0;
    virtual ~MotionFactory() = default;
};

// 具体工厂1:创建直线运动控制器
class LinearMotionFactory : public MotionFactory {
public:
    MotionController* createMotion() override {
        return new LinearMotion();
    }
};

// 具体工厂2:创建圆弧运动控制器
class ArcMotionFactory : public MotionFactory {
public:
    MotionController* createMotion() override {
        return new ArcMotion();
    }
};

// 客户端代码
int main() {
    // 使用直线运动工厂
    MotionFactory* linearFactory = new LinearMotionFactory();
    MotionController* linear = linearFactory->createMotion();
    linear->execute();  // 输出:执行直线插补运动

    // 使用圆弧运动工厂
    MotionFactory* arcFactory = new ArcMotionFactory();
    MotionController* arc = arcFactory->createMotion();
    arc->execute();     // 输出:执行圆弧插补运动

    delete linearFactory;
    delete linear;
    delete arcFactory;
    delete arc;
    return 0;
}

模式优势

解耦性:客户端仅依赖抽象接口,无需关心具体实现类。

扩展性:新增运动类型时(如螺旋运动),只需添加对应的具体产品和工厂类,无需修改已有代码,符合开闭原则。

职责清晰:将对象创建逻辑集中到工厂类,避免代码重复。


适用场景

系统需要支持多种类型的对象创建(如数控系统的不同运动模式)。

创建过程需要动态扩展(如未来新增五轴联动控制)。


对比简单工厂模式

工厂方法模式通过多态性将对象创建延迟到子类,避免了简单工厂模式中因新增类型需修改工厂类的缺点。


相关推荐
十五年专注C++开发1 小时前
设计模式之适配器模式(二):STL适配器
c++·设计模式·stl·适配器模式·包装器
渊渟岳2 小时前
掌握设计模式--中介者模式
设计模式
云徒川2 小时前
【设计模式】单例模式
设计模式
木子庆五8 小时前
Android设计模式之模板方法模式
android·设计模式·模板方法模式
Antonio91510 小时前
【设计模式】状态模式
设计模式
木子庆五13 小时前
Android设计模式之工厂方法模式
android·设计模式·工厂方法模式
Absinthe_苦艾酒1 天前
设计模式之适配器模式
设计模式·适配器模式
Zfox_1 天前
【Linux】高性能网络模式:Reactor 反应堆模式
linux·服务器·c++·设计模式·性能优化·reactor
木子庆五1 天前
Android 设计模式之适配器模式
android·设计模式·适配器模式
找了一圈尾巴2 天前
设计模式(创建型)-建造者模式
设计模式·建造者模式