代码实现:
public interface Strategy {
double getPrice(double price);
}
//新客户小批量
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("打八五折");
return price*0.85;
}
}
//老客户大批量
public class OldCustomerManyStrategy implements Strategy{
@Override
public double getPrice(double price) {
System.out.println("打八折");
return price*0.8;
}
}
/**
* 负责和具体的策略类交互
* 这样的话,具体的算法和直接的客户端调用分离了,使得算法可以独立于客户端独立的变化
* 如果使用spring的依赖注入功能,还可以通过配置文件,动态的注入不同策略对象,动态的切换不同的算法
* @author 万河归海
*
*/
public class Context {
private Strategy strategy;//当前采用 的算法对象
//可以通过构造方法注入
public Context(Strategy strategy) {
super();
this.strategy = strategy;
}
//可以用set方法注入
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void pringPrice(double s){
System.out.println("您该报价"+strategy.getPrice(s));
}
}
public class Test {
public static void main(String[] args) {
Strategy strategy = new NewCustomerManyStrategy();
Context context = new Context(strategy);
context.pringPrice(6520);
}
}