简单工厂模式和策略模式的异同

文章目录

简单工厂模式和策略模式的异同

相同点:

都涉及到对象的创建和使用。在简单工厂模式中,工厂类负责创建对象;在策略模式中,虽然重点是算法的封装和切换,但具体策略类也是对象,需要被创建。

都有助于提高代码的可维护性和可扩展性。简单工厂模式将对象创建逻辑集中在工厂类中,方便添加新的产品对象;策略模式将不同的算法封装在具体策略类中,便于添加新的策略。

不同点:

目的:

简单工厂模式主要用于创建对象,它将对象的创建和使用分离。例如,在一个游戏道具系统中,简单工厂模式可以用来创建不同类型的道具,如武器、防具等。

策略模式侧重于在运行时切换算法或行为。例如,在游戏角色的攻击行为中,可以有不同的攻击策略,如近战攻击、远程攻击等,根据游戏场景和角色状态来切换。

结构:

简单工厂模式通常有一个工厂类,包含一个创建对象的方法,根据传入的参数返回不同类型的产品对象。

策略模式包含一个策略接口、多个具体策略类和一个上下文类。策略接口定义了算法方法,具体策略类实现这些方法,上下文类持有策略接口引用,用于调用具体策略类的算法。

C++ 代码示例

简单工厂模式示例(以创建图形对象为例)

cpp 复制代码
// 抽象图形类
class Shape
 {
public:
    virtual void draw() = 0;
};

// 具体图形类 - 圆形
class Circle : public Shape 
{
public:
    void draw() override
     {
        std::cout << "Drawing a circle." << std::endl;
    }
};

// 具体图形类 - 矩形
class Rectangle : public Shape
{
public:
    void draw() override 
    {
        std::cout << "Drawing a rectangle." << std::endl;
    }
};

// 简单工厂类
class ShapeFactory 
{
public:
    static Shape* createShape(const std::string& shapeType)
     {
        if (shapeType == "circle") 
        {
            return new Circle();
        }
        else if (shapeType == "rectangle") 
        {
            return new Rectangle();
        }
        return nullptr;
    }
};


int main() 
{
    Shape* circle = ShapeFactory::createShape("circle");
    circle->draw();
    Shape* rectangle = ShapeFactory::createShape("rectangle");
    rectangle->draw();
    delete circle;
    delete rectangle;
    return 0;
}

策略模式示例(以计算价格折扣策略为例)

cpp 复制代码
// 折扣策略接口
class DiscountStrategy
{
public:
    virtual double calculateDiscount(double price) = 0;
};

// 具体折扣策略类 - 满减折扣
class FullReductionDiscount : public DiscountStrategy 
{
public:
    double calculateDiscount(double price) override 
    {
        if (price >= 100) 
        {
            return 20;
        }
        return 0;
    }
};

// 具体折扣策略类 - 会员折扣
class MemberDiscount : public DiscountStrategy 
{
public:
    double calculateDiscount(double price) override 
    {
        return price * 0.1;
    }
};

// 上下文类
class PriceContext 
{
private:
    DiscountStrategy* discountStrategy;
public:
    PriceContext(DiscountStrategy* strategy) : discountStrategy(strategy) {}
    double calculateFinalPrice(double price) 
    {
        double discount = discountStrategy->calculateDiscount(price);
        return price - discount;
    }
};


int main() 
{
    FullReductionDiscount fullReduction;
    PriceContext fullReductionContext(&fullReduction);
    double price1 = fullReductionContext.calculateFinalPrice(120);
    std::cout << "Final price after full - reduction discount: " << price1 << std::endl;
    MemberDiscount memberDiscount;
    PriceContext memberDiscountContext(&memberDiscount);
    double price2 = memberDiscountContext.calculateFinalPrice(80);
    std::cout << "Final price after member discount: " << price2 << std::endl;
    return 0;
}

在上述代码中:

简单工厂模式的代码通过ShapeFactory创建不同类型的Shape对象(Circle和Rectangle)。工厂类的createShape方法根据传入的字符串参数决定创建哪种具体的图形对象。

策略模式的代码定义了DiscountStrategy接口,有FullReductionDiscount和MemberDiscount两个具体策略类实现了不同的折扣计算方法。PriceContext作为上下文类,根据传入的折扣策略对象来计算最终价格,通过这种方式可以在运行时灵活切换折扣策略。

UML区别


相关推荐
意法半导体STM326 天前
【官方原创】如何为STM32CubeMX2配置Visual Studio Code配置方案
vscode·stm32·单片机·嵌入式硬件·策略模式·stm32cubemx·嵌入式开发
山东点狮信息科技有限公司7 天前
企业级 MES 制造执行系统架构设计与实践
spring cloud·性能优化·系统架构·策略模式·点狮
zzqssliu7 天前
基于策略模式与责任链的代购商品多源采集架构实战
架构·策略模式
mxpan8 天前
macOS 13+ 上使用 macFUSE + NTFS-3G 读写 NTFS 移动硬盘技术说明
macos·策略模式
折哥的程序人生 · 物流技术专研8 天前
Java 23 种设计模式:从踩坑到精通 | 番外:编排器+策略模式在多平台电子面单中的实战(含性能压测)
设计模式·策略模式·代码重构·java设计模式·编排器·电子面单·从踩坑到精通
忧云9 天前
2026年最新 Cursor 国内使用 DeepSeek API等各模型使用完整教程
ai编程·策略模式·cursor·byok·cursor使用国内大模型
AIex-YH9 天前
三域贯通11/12:生物制造的“死亡之谷“,CDMO 是桥还是船?
运维·制造·策略模式
回忆2012初秋10 天前
【Nginx】原理、配置与运维实战(2)
运维·nginx·策略模式
怎么没有名字注册了啊10 天前
macOS 基于 CSDN GitCode + Homebrew Tap 发布 Qt .app 二进制程序通用教程(homebrew 安装自己的软件)
策略模式·homebrew·formula·ruhy
坏小虎11 天前
macOS 安装 Ghostty 终端完整教程:环境、依赖与美化配置
macos·策略模式