【设计模式】 策略模式

策略模式(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;
}

策略模式的优缺点

优点:

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

缺点:

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

相关推荐
李广坤2 小时前
状态模式(State Pattern)
设计模式
李广坤3 小时前
观察者模式(Observer Pattern)
设计模式
李广坤4 小时前
中介者模式(Mediator Pattern)
设计模式
李广坤4 小时前
迭代器模式(Iterator Pattern)
设计模式
李广坤5 小时前
解释器模式(Interpreter Pattern)
设计模式
阿无,8 小时前
java23种设计模式之前言
设计模式
Asort9 小时前
JavaScript设计模式(八):组合模式(Composite)——构建灵活可扩展的树形对象结构
前端·javascript·设计模式
数据智能老司机9 小时前
数据工程设计模式——数据基础
大数据·设计模式·架构
笨手笨脚の11 小时前
设计模式-代理模式
设计模式·代理模式·aop·动态代理·结构型设计模式
Overboom19 小时前
[C++] --- 常用设计模式
开发语言·c++·设计模式