设计模式(五):策略模式
一、介绍
策略模式的类图
策略模式是处理算法不同变体的一种成熟模式,策略模式通过接口或抽象类封装算法的标识,即在接口中定义一个抽象方法,实现该接口的类将实现接口中的抽象方法。策略模式把针对一个算法标识的一系列具体算法分别封装在不同的类中,使得各个类给出的具体算法可以相互替换。
在策略模式中,封装算法标识的接口称作策略,实现该接口的类称作具体策略。
二、实现
假设,我们现在在为一家超市做收银系统,刚好超市这段时间做促销活动,有以下几种活动策略:
- 满200返50
- 满300返100
- 满500返200
1.定义一个策略接口
//策略接口
public interface Stragety {
double cost(double money);
}
2.根据三种活动策略,创建三种策略实现类(后面还可以和其他设计模式结合,简化代码)
//满200返50
public class StrategyA implements Stragety {
@Override
public double cost(double money) {
if(money>=200){
return money-50;
}
return money;
}
}
//满300返100
public class StrategyB implements Stragety {
@Override
public double cost(double money) {
if(money>=300){
return money-100;
}
return money;
}
}
//满500返200
public class StrategyC implements Stragety {
@Override
public double cost(double money) {
if(money>=500){
return money-200;
}
return money;
}
}
3.创建Context对象,里面关联Stragety接口,并调用其cost方法
public class Context {
private Stragety stragety;
public Context(Stragety stragety) {
this.stragety = stragety;
}
public double getCost(double money){
return this.stragety.cost(money);
}
}
4.测试
public class MainApp{
public static void main(String[] args)throws Exception {
buy(StrategyA.class,200);//满200减50
buy(StrategyB.class,300);//满300减100
buy(StrategyC.class,500);//满500减200
}
private static void buy(Class cls,double money)throws Exception{
Context context=new Context((Stragety) cls.newInstance());
double costMoney = context.getCost(money);
System.out.println("原价:"+money+"\n优惠价格:"+(money-costMoney)+"\n结算价 钱:"+costMoney+"\n");
}
}
三、总结
策略模式的结构包括三种角色:
- 策略(Strategy):策略是一个接口,该接口定义若干个算法标识,即定义了若干个抽象方法。
- 具体策略(ConcreteStrategy):具体策略是实现策略接口的类。具体策略实现策略接口所定义的抽象方法,即给出算法标识的具体算法。
- 上下文(Context):上下文是依赖于策略接口的类,即上下文包含有策略声明的变量。上下文中提供了一个方法,该方法委托策略变量调用具体策略所实现的策略接口中的方法。
用户只需要关注上下文(Context),不需要知道它内部是怎么运作的,但是,必须知道所有的具体策略以及它们之间的区别,具体使用哪种策略,就得靠用户自己选择了。