【设计模式】 策略模式

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

策略模式的优缺点

优点:

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

缺点:

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

相关推荐
ghost1434 小时前
C#学习第23天:面向对象设计模式
开发语言·学习·设计模式·c#
西北大程序猿5 小时前
日志与策略模式
策略模式
敲代码的 蜡笔小新8 小时前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式
敲代码的 蜡笔小新1 天前
【行为型之命令模式】游戏开发实战——Unity可撤销系统与高级输入管理的架构秘钥
unity·设计模式·架构·命令模式
m0_555762901 天前
D-Pointer(Pimpl)设计模式(指向实现的指针)
设计模式
小Mie不吃饭1 天前
【23种设计模式】分类结构有哪些?
java·设计模式·设计规范
君鼎2 天前
C++设计模式——单例模式
c++·单例模式·设计模式
敲代码的 蜡笔小新2 天前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
令狐前生2 天前
设计模式学习整理
学习·设计模式
敲代码的 蜡笔小新2 天前
【行为型之解释器模式】游戏开发实战——Unity动态公式解析与脚本系统的架构奥秘
unity·设计模式·游戏引擎·解释器模式