设计模型——策略模式

场景引入

个人感觉就和java中的多态性是差不多原理的,即:先定义一个接口,其中定义了一个抽象方法,比如两个数组的计算操作。然后用一些实现类去实现这个接口,实现其中具体的计算操作,比如有:加、减、乘、除。然后在使用时,我们只需要指定是哪一个具体的实现策略即可。

结构图

在这里插入图片描述

代码

策略

public interface strategy<T> {
    int operate(int o1,int o2);
}

策略实现

public class Add implements strategy{
    @Override
    public int operate(int o1, int o2) {
        return o1+o2;
    }
}
public class Divide implements strategy{
    @Override
    public int operate(int o1, int o2) {
        return o1 / o2;
    }
}

测试对象

public class TestObject {
    private strategy strategy;

    public TestObject(strategy strategy){
        this.strategy = strategy;
    }

    public int executeStrategy(int num1, int num2){
        return strategy.operate(num1, num2);
    }

}

测试结果

public class Test {
    public static void main(String[] args) {
        TestObject context = new TestObject(new Add());
        System.out.println("15 + 5 = " + context.executeStrategy(15, 5));

        context = new TestObject(new Divide());
        System.out.println("15 / 5 = " + context.executeStrategy(15, 5));

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值