首页 > 其他 > 详细

策略模式

时间:2020-04-27 01:10:40      阅读:87      评论:0      收藏:0      [点我收藏+]

策略模式:在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。

也就是说,定义一个接口,实现该接口表示为多种策略,定义一个Context对象,Context对象会跟着策略对象的改变而改变。

 1 public interface Strategy {
 2    public int doOperation(int num1, int num2);
 3 }
 4 
 5 public class OperationAdd implements Strategy{
 6    @Override
 7    public int doOperation(int num1, int num2) {
 8       return num1 + num2;
 9    }
10 }
11 
12 public class OperationSubstract implements Strategy{
13    @Override
14    public int doOperation(int num1, int num2) {
15       return num1 - num2;
16    }
17 }
18 
19 public class OperationMultiply implements Strategy{
20    @Override
21    public int doOperation(int num1, int num2) {
22       return num1 * num2;
23    }
24 }
25 
26 public class Context {
27    private Strategy strategy;
28  
29    public Context(Strategy strategy){
30       this.strategy = strategy;
31    }
32  
33    public int executeStrategy(int num1, int num2){
34       return strategy.doOperation(num1, num2);
35    }
36 }
37 
38 public class StrategyPatternDemo {
39    public static void main(String[] args) {
40       Context context = new Context(new OperationAdd());    
41       System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
42  
43       context = new Context(new OperationSubstract());      
44       System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
45  
46       context = new Context(new OperationMultiply());    
47       System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
48    }
49 }

 

策略模式

原文:https://www.cnblogs.com/seedss/p/12783801.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!