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

模式优势

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

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

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


适用场景

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

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


对比简单工厂模式

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


相关推荐
周努力.14 小时前
设计模式之中介者模式
设计模式·中介者模式
yangyang_z1 天前
【C++设计模式之Template Method Pattern】
设计模式
源远流长jerry1 天前
常用设计模式
设计模式
z26373056111 天前
六大设计模式--OCP(开闭原则):构建可扩展软件的基石
设计模式·开闭原则
01空间2 天前
设计模式简述(十八)享元模式
设计模式·享元模式
秋名RG2 天前
深入理解设计模式之原型模式(Prototype Pattern)
设计模式·原型模式
Li小李同学Li2 天前
设计模式【cpp实现版本】
单例模式·设计模式
周努力.2 天前
设计模式之状态模式
设计模式·状态模式
268572593 天前
Java 23种设计模式 - 行为型模式11种
java·开发语言·设计模式
摘星编程3 天前
并发设计模式实战系列(19):监视器(Monitor)
设计模式·并发编程