一、问题的产生
举例:鸭子模型
鸭子模型中会出现各种鸭子,会游泳,会呱呱叫,于是设计一个鸭子超类(Duck),并让各种鸭子继承此超类一、问题的产生
举例:鸭子模型
鸭子模型中会出现各种鸭子,会游泳,会呱呱叫,于是设计一个鸭子超类(Duck),并让各种鸭子继承此超类
这时,如果想让鸭子有会飞的特征,怎么办呢?加上一个fly()方法,让所有鸭子继承fly()?
结果是所有的鸭子都会飞了,哪怕是不应该会飞的橡皮鸭子,另外橡皮鸭子也不是呱呱叫而是吱吱叫,这又怎么办呢?采用覆盖的方法,把quack()和fly()覆盖成正确的方法?
如果是诱饵鸭,是一只木头假鸭,既不会飞也不会叫怎么办呢?
如果有成千上万种鸭子,都需要检查哪些方法需要覆盖吗?
二、解决办法
有一个设计原则可以解决这些问题:找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。也就是说把会变化的部分取出并封装起来,以便以后可以轻易的改到或扩充此部分,而不影响不需要变化的其他部分。
鸭子模型中,fly()和quack()是需要经常变化或修改的地方,把它们独立出来,一个和fly相关,一个和quack相关,并实现各自的动作。
如何实现这两个动作呢?如果这两种行为是在超类Duck的具体实现,或是一个接口,由子类自行实现,我们还是要在每个具体的鸭子类中实现它。
另一个设计原则告诉我们:针对接口编程,而不是针对实现编程。制造一组行为类专门实现FlyBehavior和QuackBehavior,由此行为类来实现行为接口,而不是Duck类。
最后鸭子模型的整体设计如下:
可以看出Duck类“HAS-A”(有一个→)接口实现<<interface>>FlayBehavior和<<interface>>QuackBehavior。
各种鸭子类型MallardDuck(绿头鸭)、ReadheadDuck(红头鸭)等“IS-A”(是一个
FlyWithWings、Quack等是implement(实现
“有一个HAS-A”的关系可以将各种行为(飞行,呱呱叫)委托他们处理。和“继承”不同的地方在于,鸭子的行为不是继承来的,而是适当的行为“组合”来的。
这遵循了一个设计原则:多用组合,少用继承。
这种组合的方法具有很大的弹性,不仅可将算法族封装成类,还可以“在运行时动态改变行为”。
三、策略模式(Strategy Pattern)
1、定义
策略模式定义了算法族,分别封装起来,让他们直接可以互相替换,此模式让算法的变化独立于使用算法的客户。在某一场景需要有多种情况,不同情况有不同的处理(大量 if-else 或者 switch),但大致功能是一样的,这时我们可以考虑用策略模式实现。
2、优缺点
A、优点:
1)每个算法都独立于其他,方便单元测试。
2)结构更加清晰,不会有一堆条件语句处理不同情况。
3)客户端引用的是接口,耦合度低,扩展性强。
B、缺点:
1)客户端必须知道所有的策略类,并自行决定使用哪一个策略类。这就意味着客户端必须理解这些算法的区别,以便适时选择恰当的算法类。换言之,策略模式只适用于客户端知道所有的算法或行为的情况。
2)随着策略增加,子类会增加。
3、举例
假设用户分为普通用户、会员、金牌会员,不同的用户,购买商品有不同的打折方式,一个用户每消费10000就增加一个级别,以上两种用户购买产品花费原价、九折、八折。
A、定义计算价格的策略接口
public interface CalPrice { //根据原价返回一个最终的价格
Double calPrice(Double orgnicPrice);
}
B、3种用户购买价格的计算方式的实现
public class Orgnic implements CalPrice {//普通用户
@Override
public Double calPrice(Double orgnicPrice) {
return orgnicPrice;
}
}
public class Vip implements CalPrice { //会员
@Override
public Double calPrice(Double orgnicPrice) {
return orgnicPrice * 0.9;
}
}
public class SuperVip implements CalPrice { //金牌会员
@Override
public Double calPrice(Double orgnicPrice) {
return orgnicPrice * 0.8;
}
}
C、客户类
public class Customer {
private Double totalAmount = 0;//客户消费的总额
private Double amount = 0;//客户单次消费金额
//每个客户都有一个计算价格的策略,初始都是普通计算,即原价
private CalPrice calPrice = new Orgnic();
//客户产品,就会增加它的总额
public void buy(Double amount) {
this.amount = amount;
totalAmount += amount;
if (totalAmount > 20000) {//改为金牌会员价格
calPrice = new SuperVip();
} else if (totalAmount > 10000) {//改为会员价格
calPrice = new Vip();
}
}
//计算客户最终要付的钱
public Double calLastAmount() {
return calPrice.calPrice(amount);
}
}
D、客户端调用,系统会帮我们自动调整收费策略。
public class Client {
public static void main(String[] args) {
Customer customer = new Customer();
customer.buy(5000);
System.out.println("需要付钱:" + customer.calLastAmount());
customer.buy(12000);
System.out.println("需要付钱:" + customer.calLastAmount());
customer.buy(12000);
System.out.println("需要付钱:" + customer.calLastAmount());
}
}
客户不再依赖于具体的收费策略,依赖于抽象永远是正确的。
4、在android中的应用
A、ListAdapter
如果ListView 要显示的子布局是个简单的文字时,我们可以使用 ArrayAdapter
mListView = (ListView) findViewById(R.id.list_view);
mListView.setAdapter(new ArrayAdapter<>(
this,
R.layout.item_text,
Arrays.asList("a", "b", "c")));
要显示复杂些的布局时,需要用 BaseAdapter
mListView = (ListView) findViewById(R.id.list_view);
mListView.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return mData.size();
}
@Override
public object getItem(int positon) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = ...
return converView;
}
});
可以看到,当更换Adapter的具体实现时,仍然调用的是ListView.setAdapter(…)方法,查看ListView源码,发现setAdapter方法的参数是一个 ListAdapter。
/**
* Sets the data behind this ListView.
*
* The adapter passed to this method may be wrapped by a {@Link WrapperList Adatper}
* depending ont the ListView features currently in use. For instance, adding
* headers and/or footers will cause the adapter to be wrapped.
*
* @param adapter the ListAdapter which is responsible for maintaining the
* data backing this list and for producing a view to represent an
* item in that data set.
*
* @see #getAdapter()
*/
@Overid
public void setAdapter(ListAdapter adapter) {
继续看 ListAdapter 源码和类结构
可以看到ListAdapter是一个接口,ArrayAdapter和BaseAdapter是它的一个实现类,在 ListView 中引用的是接口 ListAdapter,这就是一个策略模式的使用。
B、时间插值器TimeInterpolator
时间插值器,它是一个接口,定义了动画改变的速率,允许动画进行非匀速变化。 在使用属性动画时,可以根据需要选择合适的时间插值器
ObjectAnimator animator = ObjectAnimator.ofFloat(mListView, View.Alpha, 0f, 1f);
animator.setInterpolator(new AccelerateInterpolator()); //加速
animator.setInterpolator(new OvershootInterpolator()); //跑到头又返回来
和ListView的setAdapter一样,ValueAnimator的setInterpolator方法中也引用的是接口TimeInterpolator
/**
* The time interpolator used in calculating the elapsed fraction of this animation. The
* interpolator determines whether the animation runs with linear or non_linear mation,
* such as acceleration and deceleration. The default value is
* {@link android.view.animation.AccelerateDecelerateInterpolator}
*
* @param value the interpolator to be used by this animation. A value of <code>null</code>
* will result in linear interpolation.
*/
@Overid
public void setInterpolator(TimeInterpolator value) {
if (value != null) {
mInterpolator = value;
} else {
mInterpolator = new LinearInterpolator();
}
}
TimeInterpolator 源码及类结构