2.设计模式-----策略模式

策略模式(Strategy)

定义:(它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会直接影响到用算法的客户。)

模式分析:

    策略模式是一种定义一系列算法的模式,完成的工作相同,只是由于实现不同,所以以相同的方式调用,减少了各种算法类与使用算法类之间的耦合。

    策略模式可以封装任何类型的规则,实践过程中,只要在分析过程中听到以不同的时间运用不同的业务规则,就可以考虑用策略模式。

简单来说:方法通过参数的不同,调用了各不相同的算法逻辑,得到了自己想要的结果。

结构图:

     这个类图并不复杂,右边是策略接口以及它的实现类,左边会有一个上下文,这个上下文会拥有一个策略,而具体这个策略是哪一种,我们是可以随意替换的。

下面还是以一个计算器的代码为案例:

//抽象计算类
public interface OperationStategy {

    BigDecimal operation(BigDecimal num1,BigDecimal num2);
}
//实现OperationStategy,加法实现类
public class OperationStategyAdd implements OperationStategy {
    @Override
    public BigDecimal operation(BigDecimal num1, BigDecimal num2) {
        return num1.add(num2);
    }
}
//减法实现类
public class OperationStategySub implements OperationStategy {
    @Override
    public BigDecimal operation(BigDecimal num1, BigDecimal num2) {
        return num1.subtract(num2);
    }
}
public class Context {
    private OperationStategy operationStategy;

//   基本策略模式
//    public Context(OperationStategy operationStategy){
//        this.operationStategy = operationStategy;
//    }

    //   策略模式与简单工厂模式结合
    public Context(OperationEnum operationEnum){
        switch (operationEnum){
            case ADD:
                operationStategy = new OperationStategyAdd();
            case SUB:
                operationStategy = new OperationStategySub();
        }
    }

    public BigDecimal operation(BigDecimal num1,BigDecimal num2){
        return operationStategy.operation(num1,num2);
    }
}
/**
 * @Author: yhr
 * @Date: 2018/7/27/027 10:23
 * 实现简单计算器
 * 策略模式()
 * 应用场景:不同时间应用不同的业务规则
 */
public class RunMain {

    public static void main(String[] args) {
        //基本策略模式
        //Context context = new Context(new OperationStategyAdd());

        //策略模式与工厂模式结合
        Context context = new Context(OperationEnum.ADD);
        BigDecimal result = context.operation(new BigDecimal(3), new BigDecimal(2));
        System.out.println(result);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖醋排骨不拿拿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值