策略模式

1.策略模式简介

在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。

使用场景:
(1)如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为。
(2)一个系统需要动态地在几种算法中选择一种。
(3)如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现。


2.实现Demo
我们将创建一个定义活动的 Strategy 接口和实现了 Strategy 接口的实体策略类。Context 是一个使用了某种策略的类。
StrategyPatternDemo,我们的演示类使用 Context 和策略对象来演示 Context 在它所配置或使用的策略改变时的行为变化。

interface Stragety {
    int operation(int num1, int num2);
}

class AddStragety implements Stragety {
    public int operation(int num1, int num2) {
        return num1 + num2;
    }
}

class SubStragety implements Stragety {
    public int operation(int num1, int num2) {
        return num1 - num2;
    }
}

class MultiStragety implements Stragety {
    public int operation(int num1, int num2) {
        return num1 * num2;
    }
}



class Context {
    private Stragety stragety;

    public Context(Stragety stragety) {
        this.stragety = stragety;
    }

    public void setStragety(Stragety stragety) {
        this.stragety = stragety;
    }

    public int executeStragety(int num1, int num2) {
        return stragety.operation(num1, num2);
    }

}


public class StrategyPatternDemo {
    public static void main(String args[]) {

        Context context1 = new Context(new AddStragety());
        System.out.println("10 + 2 = " + context1.executeStragety(10, 2));

        context1.setStragety(new SubStragety());
        System.out.println("10 - 2 = " + context1.executeStragety(10, 2));

        context1.setStragety(new MultiStragety());
        System.out.println("10 * 2 = " + context1.executeStragety(10, 2));
    }
}

/*
$ java StrategyPatternDemo 
10 + 2 = 12
10 - 2 = 8
10 * 2 = 20

*/

 

 

参考:http://www.runoob.com/design-pattern/strategy-pattern.html

 

posted on 2019-04-19 00:10  Hello-World3  阅读(97)  评论(0编辑  收藏  举报

导航