用C语言能帮我实现一个策略模式的框架,方便以后我扩展自己的策略 能帮我把这个框架更细化一些,关注高内聚低耦合,并且容易复用
策略模式是一种行为型设计模式,它允许在运行时选择算法的行为。在策略模式中,算法被封装在独立的类中,以便更改或替换算法,而不会影响客户端使用算法的方式。
下面是一个用C语言实现策略模式的框架。该框架包含两个主要组件:策略接口和上下文类。
- 策略接口
策略接口定义了算法的通用接口。它定义了一个执行算法的方法,该方法接受一些参数并返回一个结果。在实现算法时,可以根据需要添加其他方法。
// 策略接口
typedef struct Strategy {
// 执行算法的方法
int (*execute)(struct Strategy*, int, int);
} Strategy;
- 上下文类
上下文类是策略模式的核心组件。它包含对策略接口的引用,并可以根据需要使用不同的策略实现来执行算法。上下文类还可以包含其他方法和属性,以便更好地与策略进行交互。
// 上下文类
typedef struct Context {
// 策略接口的引用
Strategy* strategy;
// 执行算法的方法
int (*execute)(struct Context*, int, int);
} Context;
// 执行算法
int Context_execute(Context* this, int x, int y) {
if (this->strategy != NULL) {
return this->strategy->execute(this->strategy, x, y);
}
return -1;
}
- 策略实现
策略实现是算法的具体实现。它必须实现策略接口,以便可以通过上下文类来使用。
// 策略实现
typedef struct ConcreteStrategyA {
// 策略接口
Strategy strategy;
// 实现算法的方法
int (*execute)(Strategy*, int, int);
} ConcreteStrategyA;
// 实现算法
int ConcreteStrategyA_execute(Strategy* strategy, int x, int y) {
ConcreteStrategyA* this = (ConcreteStrategyA*)strategy;
return x + y;
}
// 初始化策略实现
void ConcreteStrategyA_init(ConcreteStrategyA* this) {
this->strategy.execute = ConcreteStrategyA_execute;
}
- 使用策略模式
使用策略模式,首先需要创建一个上下文对象。然后,可以根据需要设置不同的策略实现,并使用上下文对象来执行算法。
int main() {
// 创建上下文对象
Context context;
context.strategy = NULL;
context.execute = Context_execute;
// 创建策略实现
ConcreteStrategyA strategyA;
ConcreteStrategyA_init(&strategyA);
// 使用策略实现执行算法
context.strategy = (Strategy*)&strategyA;
int result = context.execute(&context, 1, 2);
printf("result: %d\n", result);
return 0;
}
该框架具有高内聚低耦合的特点,因为每个组件都有明确定义的职责,并且它们之间的依赖性非常低。该框架还容易复用,因为可以轻松地添加新的策略实现,并将其与任何上下文对象一起使用。
原文地址: https://www.cveoy.top/t/topic/zfT 著作权归作者所有。请勿转载和采集!