java设计模式学习之策略模式

    xiaoxiao2021-03-25  107

    1.介绍 在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。比如我们在计算两个数字的时候,会有数字相加,数字相减,数字相乘,数字相除几种方法,一般做法,我们会用一个 if…else 来判断,但是这样有一个不好的地方就是代码复杂化,不利于维护,这时候可以使用策略模式。 2.代码实例 未使用策略模式的代码写法:

    public int getResult(String type, int num1, int num2) { if (type.equals("add")) { // 自己的算法 // ...... } else if (type.equals("substract")) { // 自己的算法 // ...... } else if (type.equals("multiply")) { // 自己的算法 // ...... } else if (type.equals("division")) { // 自己的算法 // ...... } return 0; }

    我们可以看出有个弊端,当这个类型特别多,而且每个类型里面还有自己的算法,如果算法比较复杂的话整个条件的控制代码会变得很长,难以维护。为了解决这个问题,我们可以使用策略模式。 先建一个接口:

    package com.tl.skyLine.pattern.StrategyPattern; /** * Created by tl on 17/3/9. */ public interface Strategy { public int operation(int num1, int num2); }

    不同的算法,实现方式: OperationAdd:

    package com.tl.skyLine.pattern.StrategyPattern; /** * Created by tl on 17/3/9. */ public class OperationAdd implements Strategy { @Override public int operation(int num1, int num2) { return num1 + num2; } }

    OperationSubstract:

    package com.tl.skyLine.pattern.StrategyPattern; /** * Created by tl on 17/3/9. */ public class OperationSubstract implements Strategy { @Override public int operation(int num1, int num2) { return num1 - num2; } }

    OperationMultiply:

    package com.tl.skyLine.pattern.StrategyPattern; /** * Created by tl on 17/3/9. */ public class OperationMultiply implements Strategy { @Override public int operation(int num1, int num2) { return num1 * num2; } }

    上下文,查看当它改变策略 Strategy 时的行为变化:

    package com.tl.skyLine.pattern.StrategyPattern; /** * Created by tl on 17/3/9. */ public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int num1, int num2) { return strategy.operation(num1, num2); } }

    测试:

    package com.tl.skyLine.pattern.StrategyPattern; /** * Created by tl on 17/3/9. */ public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubstract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); } }

    输出:

    10 + 5 = 15 10 - 5 = 5 10 * 5 = 50

    在实际中,spring的ioc就用到了策略模式,通过@Resource注解管理,注入哪个就使用哪个。

    转载请注明原文地址: https://ju.6miu.com/read-14354.html

    最新回复(0)