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

模式优势

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

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

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


适用场景

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

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


对比简单工厂模式

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


相关推荐
fakerth1 天前
【OpenHarmony】设计模式模块详解
c++·单例模式·设计模式·openharmony
alibli1 天前
一文学会设计模式之创建型模式及最佳实现
c++·设计模式
1024肥宅1 天前
前端常用模式:提升代码质量的四大核心模式
前端·javascript·设计模式
郝学胜-神的一滴1 天前
设计模式依赖于多态特性
java·开发语言·c++·python·程序人生·设计模式·软件工程
帅次1 天前
系统分析师:软件需求工程的软件需求概述、需求获取、需求分析
设计模式·重构·软件工程·团队开发·软件构建·需求分析·规格说明书
EXtreme351 天前
【数据结构】算法艺术:如何用两个栈(LIFO)优雅地模拟队列(FIFO)?
c语言·数据结构·算法·设计模式·栈与队列·摊还分析·算法艺术
1024肥宅2 天前
JavaScript常用设计模式完整指南
前端·javascript·设计模式
特立独行的猫a2 天前
C++观察者模式设计及实现:玩转设计模式的发布-订阅机制
c++·观察者模式·设计模式
better_liang2 天前
每日Java面试场景题知识点之-单例模式
java·单例模式·设计模式·面试·企业级开发
sg_knight2 天前
什么是设计模式?为什么 Python 也需要设计模式
开发语言·python·设计模式