【设计模式】 策略模式

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

策略模式的优缺点

优点:

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

缺点:

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

相关推荐
xiaolyuh12312 小时前
Spring 框架 核心架构设计 深度详解
spring·设计模式·spring 设计模式
GISer_Jing1 天前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
GISer_Jing1 天前
AI Agent:学习与适应、模型上下文协议
人工智能·学习·设计模式·aigc
小马爱打代码1 天前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
月明长歌1 天前
Javasynchronized 原理拆解:锁升级链路 + JVM 优化 + CAS 与 ABA 问题(完整整合版)
java·开发语言·jvm·安全·设计模式
会员果汁1 天前
12.设计模式-状态模式
设计模式·状态模式
且去填词1 天前
DeepSeek :基于 AST 与 AI 的遗留系统“手术刀”式治理方案
人工智能·自动化·llm·ast·agent·策略模式·deepseek
Yu_Lijing1 天前
基于C++的《Head First设计模式》笔记——抽象工厂模式
c++·笔记·设计模式
会员果汁1 天前
13.设计模式-适配器模式
设计模式·适配器模式
GISer_Jing2 天前
AI:多智能体协作与记忆管理
人工智能·设计模式·aigc