Android 策略模式学习

策略模式

这个模式定义了一系列的算法,并将每一个算法封装起来,而且使他们还可以相互替换.
策略模式让算法独立于使用他的客户而独立变化的

使用场景

1 针对一类型问题有多种处理方式,仅仅是具体行为有差别

2 需要 安全的封装多种同一类的操作

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

自己的理解

其实就是模块化的步枪 可以通过换枪管 发射不同的子弹

代码中 SubwayStrategy 就是枪管

TranficCalculator 就是枪

代码:

/**
 * 价格计算器
 */
public class TranficCalculator {
    private CalculateStrategy mStrategy;
    public TranficCalculator(CalculateStrategy strategy) {
        mStrategy = strategy;
    }

    public int getPrice(int km) {
        return mStrategy.calculatePrice(km);
    }
}
/**
 * 计算接口
 */
public interface CalculateStrategy {
    int calculatePrice(int km);
}
/**
 * 公交车
 */
public class BusStrategy implements CalculateStrategy {
    @Override
    public int calculatePrice(int km) {
        int extraTotal = km - 10;
        int extraFactor = extraTotal / 5;
        int fraction = extraTotal % 5;
        int price = 1 + extraFactor * 1;
        price = fraction > 0 ? ++price : price;
        return price;
    }
}
/**
 * 地铁
 */
public class SubwayStrategy implements CalculateStrategy {
    @Override
    public int calculatePrice(int km) {
        if (km < 6) {
            return 3;
        }
        if (km < 12) {
            return 4;
        }
        if (km < 22) {
            return 5;
        }
        if (km < 32) {
            return 6;
        }
        return 7;
    }
}

使用:

public class MainActivity extends AppCompatActivity {

    private EditText mMainEt;
    private TranficCalculator calculator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        calculator = new TranficCalculator(new SubwayStrategy());


        mMainEt = findViewById(R.id.main_et);
        findViewById(R.id.main_bt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = mMainEt.getText().toString().trim();
                int i = Integer.parseInt(trim);
                int price = calculator.getPrice(i);
                Log.e("text123", "onCreate: price = " + price);
            }
        });
        
    }
}

具体代码地址:

https://github.com/zhoudakkk/design_pattern_day05.git

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 8,218评论 2 17
  • javascript设计模式与开发实践 设计模式 每个设计模式我们需要从三点问题入手: 定义 作用 用法与实现 单...
    穿牛仔裤的蚊子阅读 4,550评论 0 13
  • 【学习难度:★☆☆☆☆,使用频率:★★★★☆】直接出处:策略模式梳理和学习:https://github.com/...
    BruceOuyang阅读 1,662评论 3 5
  • 工厂模式 单体模式 模块模式 代理模式 职责链模式 命令模式 模板方法模式 策略模式 发布-订阅模式 中介者模式 ...
    HelloJames阅读 1,099评论 0 6
  • 二十三种设计模式 - 策略模式 策略模式简介 模式动机 完成一项任务,往往可以有多种不同的方式,每一种方式称为一个...
    JustTheSame阅读 1,919评论 2 16

友情链接更多精彩内容