一、概念及类图
在策略模式中,定义一系列算法,并将每一个算法封装起来,使它们可以相互替换,策略模式让算法独立于使用它的客户而运行,是一种对象行为模式。
Strategy是抽象策略类,定义了算法的公共方法。
ConcreteStrategyA,B是具体算法类,封装了算法的具体实现。
Context表示环境类,负责维护Strategy的一个实例。
二、实例之电影票打折
//打折类:抽象策略类
public interface Discount {
public double calculate(double price);
}
//小孩打折类:具体策略类
public class ChildrenDiscount implements Discount{
@Override
public double calculate(double price) {
return price-10;
}
}
//学生打折类:具体策略类
public class StudentDiscount implements Discount{
@Override
public double calculate(double price) {
return price*0.8;
}
}
//会员打折类:具体策略类
public class VipDiscount implements Discount{
@Override
public double calculate(double price) {
System.out.println("加积分");
return price*0.5;
}
}
//电影票类:环境类
public class MovieTicket {
private double price;
private Discount discount;
public MovieTicket(double price){
this.price=price;
}
public double getPrice(){
return discount.calculate(this.price);
}
public void setDiscount(Discount discount){
this.discount=discount;
}
}
//客户端类
public class Client {
public static void main(String[] args) {
MovieTicket movieTicket=new MovieTicket(50);
double currentPrice;
Discount discount;
discount=new StudentDiscount();
movieTicket.setDiscount(discount);
currentPrice=movieTicket.getPrice();
System.out.println("学生票为:"+currentPrice);
System.out.println("------------------------");
discount=new VipDiscount();
movieTicket.setDiscount(discount);
currentPrice=movieTicket.getPrice();
System.out.println("会员票为:"+currentPrice);
}
}
三、总结
1、通过策略模式的使用可以封装不同的算法,让算法独立于使用它的客户。
2、基本的策略模式中,选择所使用的策略的职责是由客户端来承担,则客户端必须知道所有的策略类,并自行决定要使用哪一个策略类,也就是说客户端需要知道算法的区别。
3、为了减轻客户端选择具体策略的责任,可以结合简单工厂模式,将选择的具体实现放入Context环境类中,这样就可以最大程度减轻客户端的责任。
People can’t do something by themselves,then they will tell you that you can not do it.