设计模式之策略模式

最近在学习大话设计模式,写一下自己的学习体会和实现小例子。

定义:它定义的算法家族,分别封装起来,让他们之间可以相互替换

理解:策略模式封装的算法,其实就是对同一工作的不同实现方式,使用策略模式可以减少客户端的判断,同时有利于不同算法的测试,在开发中当不同时间段使用不同的规则就可以使用策略模式

简单举例

interface:

public interface Strategy {

    int result(int a, int b);
}

 实现类:加法:

public class Add implements Strategy {
    @Override
    public int result(int a, int b) {
        return a + b;
    }
}

 

减法:

public class Reduce implements Strategy {
    @Override
    public int result(int a, int b) {
        return a - b;
    }
}

集群类:

public class Context {

    private Strategy strategy = null;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int getResult(int a, int b) {
        return strategy.result(a, b);
    }
}

 Test:

public class Main {
    public static void main(String[] args) {
        Context context = new Context(new Add());
        System.out.println(context.getResult(10, 20));
    }
}

这样策略模式就算是完成了;

另外策略模式可以和简单工厂模式结合使用:

集合类的代码更改:

public Context(int type) {
    switch (type) {
        case Constant.add:
            strategy = new Add();
            break;
        case Constant.reduce:
            strategy = new Reduce();
            break;
        default:
    }
}

 测试代码:

public static void main(String[] args) {
    Context context = new Context(new Add());
    System.out.println(context.getResult(10, 20));

    Context context1 = new Context(Constant.reduce);
    System.out.println(context1.getResult(10, 5));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值