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

模式优势

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

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

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


适用场景

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

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


对比简单工厂模式

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


相关推荐
在未来等你17 小时前
AI Agent设计模式 Day 3:Self-Ask模式:自我提问驱动的推理链
设计模式·llm·react·ai agent·plan-and-execute
xiaodaidai丶1 天前
设计模式之策略模式
设计模式·策略模式
_院长大人_1 天前
设计模式-工厂模式
java·开发语言·设计模式
王道长服务器 | 亚马逊云2 天前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
在未来等你2 天前
AI Agent设计模式 Day 1:ReAct模式:推理与行动的完美结合
设计模式·llm·react·ai agent·plan-and-execute
乐悠小码2 天前
Java设计模式精讲---03建造者模式
java·设计模式·建造者模式
_院长大人_2 天前
设计模式-代理模式
设计模式·代理模式
guangzan2 天前
TypeScript 中的单例模式
设计模式
乐悠小码3 天前
Java设计模式精讲---02抽象工厂模式
java·设计模式·抽象工厂模式
乙己4074 天前
设计模式——原型模式(prototype)
设计模式·原型模式