设计模式(21)-策略模式及实现
基本概念
提供了一种定义一系列算法的方法,将这些算法封装成独立的策略类,并使它们可以相互替换。在客户端中,创建一个上下文(Context)对象,该对象包含一个对策略类的引用,通过该引用调用相应的策略方法。这样,客户端可以在运行时选择不同的策略,而不需要修改上下文类。
优点:
实现了算法的解耦,使得算法可以独立于客户端而变化。它提高了代码的可维护性和扩展性,因为新的策略可以很容易地添加到系统中。
缺点:
策略模式也可能导致类的数量增加,因为每个算法都需要一个对应的策略类。在使用策略模式时,需要权衡类的数量与灵活性之间的关系。
https://gitee.com/want-to-lose-another-30-jin/design-pattern-implementation
设计模式具体实现
角色
1、策略接口(Strategy):
定义了所有支持的算法的公共接口。
2、具体策略类(Concrete Strategy):
实现策略接口,提供具体的算法实现。
3、上下文(Context):
使用策略接口来配置和使用具体的策略对象。
java实现
package shejimoshi.celuemoshi;
// 策略接口
public interface Strategy {
int execute(int a, int b);
}
package shejimoshi.celuemoshi;
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public int performOperation(int a, int b) {
return strategy.execute(a, b);
}
}
package shejimoshi.celuemoshi;
// 具体策略A
public class ConcreteStrategyA implements Strategy {
public int execute(int a, int b) {
return a + b;
}
}
package shejimoshi.celuemoshi;
// 具体策略B
public class ConcreteStrategyB implements Strategy {
public int execute(int a, int b) {
return a - b;
}
}
package shejimoshi.celuemoshi;
public class client {
public static void main(String[] args) {
Context context = new Context();
context.setStrategy(new ConcreteStrategyA());
System.out.println("Operation with strategy A: " + context.performOperation(10, 5));
context.setStrategy(new ConcreteStrategyB());
System.out.println("Operation with strategy B: " + context.performOperation(10, 5));
}
}
c++实现
#include <iostream>
// 策略接口
class Strategy {
public:
virtual ~Strategy() {}
virtual int execute(int a, int b) = 0;
};
// 具体策略A
class ConcreteStrategyA : public Strategy {
public:
int execute(int a, int b) override {
return a + b;
}
};
// 具体策略B
class ConcreteStrategyB : public Strategy {
public:
int execute(int a, int b) override {
return a - b;
}
};
// 上下文
class Context {
private:
Strategy* strategy;
public:
Context() : strategy(nullptr) {}
~Context() {
delete strategy;
}
void setStrategy(Strategy* strategy) {
if (this->strategy) delete this->strategy;
this->strategy = strategy;
}
int performOperation(int a, int b) {
return strategy->execute(a, b);
}
};
// 客户端
int main() {
Context context;
Strategy* strategyA = new ConcreteStrategyA();
context.setStrategy(strategyA);
std::cout << "Operation with strategy A: " << context.performOperation(10, 5) << std::endl;
Strategy* strategyB = new ConcreteStrategyB();
context.setStrategy(strategyB);
std::cout << "Operation with strategy B: " << context.performOperation(10, 5) << std::endl;
return 0;
}