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;
}

模式优势

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

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

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


适用场景

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

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


对比简单工厂模式

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


相关推荐
GISer_Jing5 小时前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
GISer_Jing5 小时前
AI Agent:学习与适应、模型上下文协议
人工智能·学习·设计模式·aigc
小马爱打代码7 小时前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
月明长歌7 小时前
Javasynchronized 原理拆解:锁升级链路 + JVM 优化 + CAS 与 ABA 问题(完整整合版)
java·开发语言·jvm·安全·设计模式
会员果汁7 小时前
12.设计模式-状态模式
设计模式·状态模式
Yu_Lijing8 小时前
基于C++的《Head First设计模式》笔记——抽象工厂模式
c++·笔记·设计模式
会员果汁11 小时前
13.设计模式-适配器模式
设计模式·适配器模式
GISer_Jing1 天前
AI:多智能体协作与记忆管理
人工智能·设计模式·aigc
雨中飘荡的记忆1 天前
责任链模式实战应用:从理论到生产实践
设计模式
沛沛老爹1 天前
Web开发者进阶AI:Agent技能设计模式之迭代分析与上下文聚合实战
前端·人工智能·设计模式