码迷,mamicode.com
首页 > 其他好文 > 详细

策略模式

时间:2019-04-19 00:49:53      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:种类型   条件选择   span   实现   接口   更改   inter   interface   cut   

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

 

策略模式

标签:种类型   条件选择   span   实现   接口   更改   inter   interface   cut   

原文地址:https://www.cnblogs.com/hellokitty2/p/10733464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!