【设计模式】 策略模式

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

策略模式的优缺点

优点:

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

缺点:

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

相关推荐
鼠鼠我呀225 分钟前
【设计模式04】单例模式
单例模式·设计模式
缘来是庄9 小时前
设计模式之访问者模式
java·设计模式·访问者模式
hqxstudying12 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
花好月圆春祺夏安13 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
fie888913 小时前
浅谈几种js设计模式
开发语言·javascript·设计模式
哆啦A梦的口袋呀13 小时前
《深入设计模式》模式结构汇总
设计模式
花好月圆春祺夏安13 小时前
基于odoo17的设计模式详解---单例模式
单例模式·设计模式
在未来等你16 小时前
设计模式精讲 Day 22:模板方法模式(Template Method Pattern)
设计模式·模板方法模式·软件架构·java开发·面向对象设计·设计模式实战·java应用开发
花好月圆春祺夏安17 小时前
基于odoo17的设计模式详解---代理模式
设计模式·代理模式
Small black human1 天前
设计模式-应用分层
设计模式