大话设计模式-策略模式

场景:商场收银时如何促销,用打折还是返利,其实都是一些算法,用工厂来生成算法,这没有错,但算法本身只是一种策略,最重要的是这些算法随时都可能互相替换,这就是变化点,而封装变化点是面向对象很重要的思维方式。

策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。

 1. 策略抽象类、打折策略类、满减策略类

package com.hj.designPattern.behavior.strategy;

public abstract class AbstractStrategy {
    public abstract double countTotal(int total);
}


package com.hj.designPattern.behavior.strategy;

public class Dazhe extends AbstractStrategy {
    @Override
    public double countTotal(int total) {
        System.out.println(total *0.8);
        return total*0.8;
    }
}


package com.hj.designPattern.behavior.strategy;

public class Manjian extends AbstractStrategy {
    @Override
    public double countTotal(int total) {
        if(total>200){
            total = total - 30;
        }
        System.out.println(total);
        return total;
    }
}

2. 上下文类

package com.hj.designPattern.behavior.strategy;


public class StrategyContext {
    private AbstractStrategy abstractStrategy;

    StrategyContext(AbstractStrategy abstractStrategy){
        this.abstractStrategy = abstractStrategy;
    }

    public void strategyInterface(int total){
        abstractStrategy.countTotal(total);
    }
}

3. 测试类

package com.hj.designPattern.behavior.strategy;

public class StrategyTest {
    public static void main(String[] args) {
        int total =1000;
        StrategyContext strategyContext = new StrategyContext(new Dazhe());
        strategyContext.strategyInterface(total);

        strategyContext = new StrategyContext(new Manjian());
        strategyContext.strategyInterface(total);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值