大话设计模式 —— 策略模式

一、模式介绍

       策略模式适合封装算法的不同实现(比如上文 大话设计模式 —— 简单工厂模式 中的数学运算)

       策略模式能够将实现的细节进一步封装,客户端代码无需知道具体算法实体是什么,就可以完成正确的运算

       上文中,客户端(Main.java)实际上是需要了解 Operation 运算父类的,而使用策略模式能够将其屏蔽,进一步解耦

       策略模式,将工厂类变成策略类,根据传入参数不同生产不同策略对象(内置),然后提供公开方法

二、使用策略模式实现计算器

       上文中的 Operation 接口 、AddOperation、SubOperation、DefaultOperation 继续复用

       我们定义一个算法策略

public class ComputeContext {

    private Operation opt;

    public ComputeContext(String operate) {
        switch (operate) {
        case "+":
            opt = new AddOperation();
            break;
        case "-":
            opt = new SubOperation();
            break;
        default:
            opt = new DefaultOperation();
        }
    }

    public int compute(int num1, int num2) {
        return opt.compute(num1, num2);
    }

}

       测试类(Main 不需要知道 Operation 类的存在,相比简单工厂,进一步解耦了)

public class Main {

    public static void main(String[] args) {
        ComputeContext ctx = new ComputeContext("+");
        System.out.println(ctx.compute(1, 2));
        ctx = new ComputeContext("-");
        System.out.println(ctx.compute(1, 2));
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值