场景:商场收银时如何促销,用打折还是返利,其实都是一些算法,用工厂来生成算法,这没有错,但算法本身只是一种策略,最重要的是这些算法随时都可能互相替换,这就是变化点,而封装变化点是面向对象很重要的思维方式。
策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
1. 策略抽象类、打折策略类、满减策略类
package com.hj.designPattern.behavior.strategy;
public abstract class AbstractStrategy {
public abstract double countTotal(int total);
}
package com.hj.designPattern.behavior.strategy;
public class Dazhe extends AbstractStrategy {
@Override
public double countTotal(int total) {
System.out.println(total *0.8);
return total*0.8;
}
}
package com.hj.designPattern.behavior.strategy;
public class Manjian extends AbstractStrategy {
@Override
public double countTotal(int total) {
if(total>200){
total = total - 30;
}
System.out.println(total);
return total;
}
}
2. 上下文类
package com.hj.designPattern.behavior.strategy;
public class StrategyContext {
private AbstractStrategy abstractStrategy;
StrategyContext(AbstractStrategy abstractStrategy){
this.abstractStrategy = abstractStrategy;
}
public void strategyInterface(int total){
abstractStrategy.countTotal(total);
}
}
3. 测试类
package com.hj.designPattern.behavior.strategy;
public class StrategyTest {
public static void main(String[] args) {
int total =1000;
StrategyContext strategyContext = new StrategyContext(new Dazhe());
strategyContext.strategyInterface(total);
strategyContext = new StrategyContext(new Manjian());
strategyContext.strategyInterface(total);
}
}