策略模式
使用场景
在某一场景需要有多种情况,不同情况有不同的处理(大量 if-else 或者 switch),但大致功能是一样的,这时我们可以考虑用策略模式实现。
优点
- 每个算法都独立于其他,方便单元测试
- 结构更加清晰,不会像一堆条件语句让你看着头晕
- 客户端引用的是接口,耦合度更低,扩展性更强
缺点
- 随着策略增加,子类会增加
可以看到,策略模式中主要有以下几个角色:
- Strategy 接口,用于定义算法的固定套路
- ConcreteStrategyA , …..B , 等具体算法实现类
- Context 外部调用类
策略模式例子 1 : ListAdapter
在 RecyclerView 还没火起来前,ListView 是一个很重要的组件,我们通常在布局里写个 ListView 组件,然后在代码中 setAdapter,把 View 与 Model 结合的任务交给了 Adapter。
- 比如 ListView 要显示的子布局是个简单的文字时,我们可以使用 ArrayAdapter :
- 要显示复杂些的布局时,就需要用 BaseAdapter :
-
我们可以看到,当更换 Adapter 的具体实现时,仍然调用的是 ListView.setAdapter(…) 方法,查看 ListView 源码,发现 setAdapter 方法的参数是一个 ListAdapter:
-
可以看到 ListAdapter 是一个接口,ArrayAdapter 和 BaseAdapter 是它的一个实现类。对比文章开始给出的 策略模式 UML 图,可以发现 ListAdapter 就是 strategy 接口,ArrayAdpater 等就是具体的实现类,而在 ListView 中引用的是 接口 ListAdapter,可以证实这就是一个 策略模式 的使用。
1:首先定义一个接口
public interface NumberPrice{
public float getPrice(float price);
}
2:定义三个实现类
public class NumberPrice1 implements NumberPrice{
private float getPrice(float price){
reture price*0.9;
};
}
public class NumberPrice2 implements NumberPrice{
private float getPrice(float price){
return price*0.8;
};
}
public class NumberPrice3 implements NumberPrice{
private float getPrice(float price){
return price*0.7;
};
}
3.定义一个策略类
public class Price{
private NumberPrice numberPrice;
public void price(NumberPrice numberPrice){
this.numberPrice=numberPrice;
}
private float getPrice(float price){
numberPrice.getPrice(price);
}
4.定义一个客户端
public void client{
private float 100;
NumberPrice numberPrice=new numberPrice1();
price pri=new price(numberPrice);
pri.getPrice(100);
}
浙公网安备 33010602011771号