策略模式

策略模式主要用来分离算法, 在相同的行为抽象下有不同的具体实现策略. 这个模式很好的演示了开闭原则, 也就是定义抽象, 注入不同的实现, 从而达到很好的可扩展性.
优点:
1. 结构清晰明了, 使用简单直观;
2. 耦合度相对而言较低, 扩展方便;
3. 操作封装也更为彻底, 数据更为安全;
缺点:
随着策略的增加, 子类也会变得繁多;
mvp引用了策略模式的思想:
需求:
选择交通方式多, 目前有公交和地铁交通方式, 以后可能还会增加其他交通方式, 每种交通方式的价格与公里的关系都不同. 用代码完成这个需求, 如果不知道策略模式的情况下, 写的代码很可能想下面代码:

public class CalculateTest {
    /** 0:公交, 1:地铁 */
    public int mTrafficMode;

    public static void main(String[] args) {
        CalculateTest calculateTest = new CalculateTest();
        calculateTest.calculatePrice(10, 0);
    }

    public int calculatePrice(int km, int trafficMode) {
        if (trafficMode == 0) {
            if (km < 5) {
                return 2;
            } else if (km < 6) {
                return 3;
            } else if (km < 7) {
                return 4;
            }
            return 5;
        } else if (trafficMode == 1) {
            if (km < 5) {
                return 3;
            } else if (km < 6) {
                return 4;
            } else if (km < 7) {
                return 5;
            }
            return 6;
        }
        return 0;
    }
}

上面代码最终会导致CalculateTest中的逻辑代码非常繁杂凌乱, 如果是在Android中, 就会导致mvp的view中的逻辑代码非常多, 降低了代码的可复用性, 不利于扩展.
如果采用策略模式:

public interface CalculateStrategy {
    int calculatePrice(int km);
}
public class BusStrategy implements CalculateStrategy {
    public int calculatePrice(int km) {
        if (km < 5) {
            return 2;
        } else if (km < 6) {
            return 3;
        } else if (km < 7) {
            return 4;
        }
        return 5;
    }
}
public class SubmwayStrategy implements CalculateStrategy {
    public int calculatePrice(int km) {
        if (km < 5) {
            return 3;
        } else if (km < 6) {
            return 4;
        } else if (km < 7) {
            return 5;
        }
        return 6;
    }
}
public class StrategyTest {
    public CalculateStrategy mStrategy;

    public static void main(String[] args) {
        StrategyTest strategyTest = new StrategyTest();
        strategyTest.setStrategy(new BusStrategy());
        int price = strategyTest.calculatePrice(10);
        System.out.println("price:" + price);
    }

    public void setStrategy(CalculateStrategy strategy) {
        mStrategy = strategy;
    }

    public int calculatePrice(int km) {
        return mStrategy.calculatePrice(km);
    }
}

只需要在StrategyTest中暴露一个setStrategy接口即可;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值