1.什么是策略模式
- 定义了一系列的算法 或 逻辑 或 相同意义的操作,并将每一个算法、逻辑、操作封装起来,而且使它们还可以相互替换。(其实策略模式Java中用的非常非常广泛)
我觉得主要是为了 简化 if…else 所带来的复杂和难以维护。
2.策略模式应用场景
策略模式的用意是针对一组算法或逻辑,将每一个算法或逻辑封装到具有共同接口的独立的类中,从而使得它们之间可以相互替换。
定义抽象的公共方法 ```java //策略模式 定义抽象方法 所有支持公共接口 abstract class PayStrategy {
// 支付逻辑方法 abstract void algorithmInterface();
}
2. 定义实现微信支付```javaclass PayStrategyA extends PayStrategy {void algorithmInterface() {System.out.println("微信支付");}}
定义实现支付宝支付
class PayStrategyB extends PayStrategy { void algorithmInterface() { System.out.println("支付宝支付"); } }定义实现银联支付
class PayStrategyC extends PayStrategy { void algorithmInterface() { System.out.println("银联支付"); } }定义下文维护算法策略 ```java class Context {
PayStrategy strategy;
public Context(PayStrategy strategy) {
this.strategy = strategy;}
public void algorithmInterface() {
strategy.algorithmInterface();}
}
6. 运行测试
```java
class ClientTestStrategy {
public static void main(String[] args) {
Context context;
//使用支付逻辑A
context = new Context(new PayStrategyA());
context.algorithmInterface();
//使用支付逻辑B
context = new Context(new PayStrategyB());
context.algorithmInterface();
//使用支付逻辑C
context = new Context(new PayStrategyC());
context.algorithmInterface();
}
}
