策略模式——《Android源码设计模式解析与实践》读书笔记7

定义

将一系列相关的算法中的每一个都封装起来,并使它们可以相互替换,即使算法可以独立于调用者。


使用场景

(1)针对同一类型的问题的多种处理方式仅是具体行为有差别时

(2)需要安全地封装多种同一类型的操作时

(3)出现同一抽象类有多个子类,而又需要使用if-else或者switch-case来选择具体子类时


UML类图


策略模式——《Android源码设计模式解析与实践》读书笔记7_第1张图片
策略模式,多角色


实现方式(省略Director类和抽象的Buidler父类)

Stragety接口

public interface Stragety{

    int algorithm();

}

Stragety类A

public class StragetyA implements Stragety{

    @Override

    public int algorithm(){

        return 1;

    }

}

Stragety类B

public class StragetyB implements Stragety{

    @Override

    public int algorithm(){

        return 2;

    }

}

Context类:

public class Context{

    Stragety mStragety;

    public void setStragety(Stragety stragety){

        this.mStragety = stragety

    }

    public int algorithm(){

        return mStragety.algorithm();

    }

}

调用例子:

public void class Test{

    public staticvoid main(String [] args){

        StragetyA a = new StragetyA();

        Context context = new Context();

        context.setStragety(a);

        context.algorithm();

    }

}


策略模式的优缺点

优点

>结构清晰明了,使用简单直观

>耦合度相对而言较低,扩展方便

>操作封装较为彻底,数据对外封闭,更安全

缺点

>随着策略的增加,子类会变得繁多


Android中的策略模式举例

TimeInterpolator,时间插值器,在动画中使用


——2017.08.08

你可能感兴趣的:(策略模式——《Android源码设计模式解析与实践》读书笔记7)