策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
本质:分离算法,选择实现。
1.Strategy:定义所有支持的算法(打折算法)的公共接口。
public interface Strategy {
double getPrice(double price);
}
2.实现Strategy接口,实现具体的算法
public class NewCustomerFewStrategy implements Strategy {
@Override
public double getPrice(double price) {
System.out.println("不打折,原价");
return price;
}
}
public class NewCustomerManyStrategy implements Strategy {
@Override
public double getPrice(double price) {
System.out.println("打九折");
return price*0.9;
}
}
public class OldCustomerFewStrategy implements Strategy {
@Override
public double getPrice(double price) {
System.out.println("打85折");
return price*0.85;
}
}
public class OldCustomerManyStragety implements Strategy {
@Override
public double getPrice(double price) {
System.out.println("打八折");
return 0.8*price;
}
}
3.根据传入的对象,调用其算法方法
/**
* 负责和具体的策略类交互
* 具体算法和客户端分离
*/
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void printPrice(double price){
System.out.println("报价:"+strategy.getPrice(price));
}
}
4.实例化不同的策略对象,调用算法时获得结果也不同
public class TestStrategy {
public static void main(String[] args) {
Strategy strategy=new NewCustomerFewStrategy();
Context context=new Context(strategy);
context.printPrice(1000);
Strategy strategy2=new NewCustomerManyStrategy();
Context context1=new Context(strategy2);
context1.printPrice(1000);
Strategy strategy3=new OldCustomerFewStrategy();
Context context2=new Context(strategy3);
context2.printPrice(1000);
Strategy strategy4=new OldCustomerManyStragety();
Context context3=new Context(strategy4);
context3.printPrice(1000);
}
}
结合工厂模式:
public class Context {
private static Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public static Strategy Cash(int string){
switch (string){
case 1:
strategy= new NewCustomerFewStrategy();
break;
case 2:
strategy=new NewCustomerManyStrategy();
break;
case 3:
strategy=new OldCustomerFewStrategy();
break;
case 4:
strategy=new OldCustomerManyStragety();
break;
}
return strategy;
}
public void printPrice(double price){
System.out.println("报价:"+strategy.getPrice(price));
}
}
public class TestStrategy {
public static void main(String[] args) {
System.out.println("请选择打折力度:1.不打折;2.九折;3.八五折;4.八折");
Scanner input=new Scanner(System.in);
int s = input.nextInt();
Context context=new Context(Context.Cash(s));
context.printPrice(1000);
}
}
策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
策略模式就是用来封装算法的,需要在不同时间应用不同的业务规则,就可以考虑使用策略模式来处理。