【设计模式】 策略模式

策略模式(Strategy Pattern)是一种行为型设计模式,它定义了一系列算法,将每个算法封装起来,使它们可以相互替换,让客户端代码和算法的具体实现解耦。这样,客户端可以根据不同的需求选择不同的算法,而无需修改原有的代码。

C 实现策略模式

c 复制代码
#include <stdio.h>
#include <stdlib.h>

// 定义策略接口
typedef struct {
    void (*execute)(void);
} Strategy;

// 具体策略1
void strategy1_execute(void) {
    printf("Executing Strategy 1\n");
}

// 具体策略2
void strategy2_execute(void) {
    printf("Executing Strategy 2\n");
}

// 客户端代码,使用策略接口
void client_code(Strategy* strategy) {
    strategy->execute();
}

int main() {
    // 创建策略对象
    Strategy* strategy1 = (Strategy*)malloc(sizeof(Strategy));
    strategy1->execute = strategy1_execute;

    Strategy* strategy2 = (Strategy*)malloc(sizeof(Strategy));
    strategy2->execute = strategy2_execute;

    // 使用不同的策略
    client_code(strategy1);
    client_code(strategy2);

    // 释放内存
    free(strategy1);
    free(strategy2);

    return 0;
}

C++ 实现策略模式

cpp 复制代码
#include <iostream>

// 定义策略接口
class Strategy {
public:
    virtual void execute() = 0;
    virtual ~Strategy() {}
};

// 具体策略1
class Strategy1 : public Strategy {
public:
    void execute() override {
        std::cout << "Executing Strategy 1" << std::endl;
    }
};

// 具体策略2
class Strategy2 : public Strategy {
public:
    void execute() override {
        std::cout << "Executing Strategy 2" << std::endl;
    }
};

// 客户端代码,使用策略接口
void client_code(Strategy* strategy) {
    strategy->execute();
}

int main() {
    // 使用不同的策略
    Strategy1 strategy1;
    Strategy2 strategy2;

    client_code(&strategy1);
    client_code(&strategy2);

    return 0;
}

策略模式的优缺点

优点:

灵活性增强 :策略模式使得算法独立于客户端使用而变化。可以在运行时动态选择算法,灵活应对不同的需求和场景。
代码重用 :各个策略可以被多个客户端共享,避免了代码重复。
扩展性良好 :当需要添加新的算法时,只需增加新的策略类,而不需要修改已有的代码。
易于测试:由于策略类封装了具体的算法,因此易于进行单元测试。

缺点:

增加类数量 :每个具体策略都需要一个对应的类,如果策略较多,可能会增加类的数量,增加代码维护的复杂性。
客户端必须了解策略 :客户端代码必须了解所有的策略,以便进行选择,如果策略较多,可能会增加客户端代码的复杂性。
总体来说,策略模式适用于需要在运行时动态选择算法,并且希望算法和客户端代码解耦的情况。对于简单的情况,可能没有必要使用策略模式,但在复杂的场景下,它可以带来更好的可维护性和可扩展性。

相关推荐
秋难降9 分钟前
代码界的 “建筑师”:建造者模式,让复杂对象构建井然有序
java·后端·设计模式
快乐的划水a3 小时前
解释器模式及优化
c++·设计模式·解释器模式
##学无止境##6 小时前
Java设计模式-观察者模式
java·观察者模式·设计模式
long31610 小时前
状态设计模式
java·学习·程序人生·设计模式·状态模式·state-pattern
秋难降14 小时前
老板让我一天加 3 种支付方式,我用工厂模式躺赢了
java·设计模式
Meteors.15 小时前
23种设计模式——单例模式(Singleton)详解
单例模式·设计模式
MasterNeverDown1 天前
ASP.NET Core 中的构建者模式
设计模式·建造者模式
jiayi1 天前
从 0 到 1 带你打造一个工业级 TypeScript 状态机
前端·设计模式·状态机
yw00yw1 天前
常见的设计模式
开发语言·javascript·设计模式
我们从未走散1 天前
设计模式学习笔记-----抽象责任链模式
java·笔记·学习·设计模式·责任链模式