作用
- 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
何时使用
- 一个系统有许多许多类,而区分它们的只是他们直接的行为。
优点
- 算法可以自由切换。
- 避免使用多重条件判断。
- 扩展性良好。
实例
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/25 11:26
* @Version:
* @Acton:
*/
public class TestStrategyDemo {
public static void main(String[] args){
test1();
}
public static void test1(){
OldCustomerManyStrategy oldCus = new OldCustomerManyStrategy();
Context context = new Context(oldCus);
context.printPrice(998);
}
}
/**
* @Author: create_By: chenxin
* @Data:Created in 2018/9/25 11:04
* @Version:
* @Acton:
*/
public class NewCustomerFewStrategy implements Strategy {
@Override
public double getPrice(double originalPrice) {
System.out.println("不打折,原价");