设计模式普及之策略模式

定义

 将一系列的算法封装起来,而且可以相互替换。让算法独立于使用它的客户而独立变化。

使用场景

  • 针对同一问题有多种处理方式,而仅仅是方式有差异。
  • 需要安全的封装多种同一类型的操作时。
  • 出现同一抽象类有多个子类,需要使用switch语句或者if语句选择时。

举例

 其实有很多例子,我这里想到买菜的场景。
 来看代码简单实现:
public interface ICalculator {
    /**
     * 根据重量计算最终价格
     * @param weight 重量kg
     * @return 最终的价格
     */
    float calculatorPrice(float weight);
}
public class Apple implements ICalculator {

    @Override
    public float calculatorPrice(float weight) {
        float nowPrice = 1.5f;
        return nowPrice * weight;
    }
}
public class Orange implements ICalculator {
    @Override
    public float calculatorPrice(float weight) {
        float nowPrice = 2.0f;
        return nowPrice * weight;
    }
}
public class PriceCalculator {
    private ICalculator calculator;

    public void setCalculator(ICalculator calculator){
        this.calculator = calculator;
    }

    public float calculatorPrice(float weight){
        return calculator.calculatorPrice(weight);
    }

    //省事了点,调用直接在类中了
    @Test
    public void checkOut(){
        PriceCalculator calculator = new PriceCalculator();

        calculator.setCalculator(new Apple());
        System.out.println("买1斤苹果花的钱》》"+calculator.calculatorPrice(1f));

        calculator.setCalculator(new Orange());
        System.out.println("买1斤桔子花的钱》》"+calculator.calculatorPrice(1f));
    }

}

总结

策略模式主要用来分离算法,在相同的抽象条件拥有不同的策略。充分展示了开闭原则,使我们的代码可以有很好的扩展性。

优点

  • 结构清晰、使用简单;
  • 耦合性低,好扩展;
  • 封装性好,数据隐蔽。

缺点

  • 算法多了,子类也就多了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值