策略模式和简单工厂模式的结合使用

1 //策略类,定义所有支持的算法的公共接口
2 public abstract class Strategy {
3     public abstract void algorithmMethod(int numberA,int numberB);
4 }
 1 //具体策略类,封装了具体的算法或行为,继承于Strategy   
 2 //用于加法的算法
 3 public class ConcreteStrategyAdd extends Strategy {
 4 
 5     @Override
 6     public void algorithmMethod(int numberA,int numberB) {
 7         System.out.println(numberA+" + "+numberB+" = "+(numberA+numberB)+";");
 8     }
 9 
10 }
 1 //具体策略类,封装了具体的算法或行为,继承于Strategy
 2 //用于乘法的算法
 3 public class ConcreteStrategyMul extends Strategy {
 4 
 5     @Override
 6     public void algorithmMethod(int numberA,int numberB) {
 7         System.out.println(numberA+" * "+numberB+" = "+(numberA*numberB)+";");
 8     }
 9 
10 }
 1 //具体策略类,封装了具体的算法或行为,继承于Strategy
 2 //用于两个数相减的算法
 3 public class ConcreteStrategySub extends Strategy {
 4 
 5     @Override
 6     public void algorithmMethod(int numberA,int numberB) {
 7         System.out.println(numberA+" - "+numberB+" = "+(numberA-numberB)+";");
 8     }
 9 
10 }

Context中改动了一些代码,和简单工厂模式结合使用:

 1 //Context上下文,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
 2 public class Context {
 3     private Strategy strategy;
 4 
 5     // 构造方法,注意,参数不是具体的算法策略对象,而是一个字符串,表示策略的类型
 6     public Context(String strategyType) {
 7         
 8         /**
 9          * 将实例化具体策略的过程由客户端转移到Context类中,简单工厂的应用
10          */
11         switch (strategyType) {
12             case "add":
13                 strategy = new ConcreteStrategyAdd();
14                 break;
15             case "sub":
16                 strategy = new ConcreteStrategySub();
17                 break;
18             case "mul":
19                 strategy = new ConcreteStrategyMul();
20                 break;
21         }
22 
23     }
24 
25     // 根据具体的策略对象,调用其算法的方法
26     public void contextInterface(int numberA, int numberB) {
27         strategy.algorithmMethod(numberA, numberB);
28     }
29 
30 }

测试类:测试类中注释掉的代码是没有结合简单工厂模式的时候在客户端写的代码。

 1 public class Test {
 2     public static void main(String[] args) {
 3         Context context;
 4         // 我想使用加法算法
 5         /*context = new Context(new ConcreteStrategyAdd());
 6         context.contextInterface(5, 4);*/
 7         context = new Context("add");
 8         context.contextInterface(5, 4);
 9 
10         // 我想使用减法算法
11         /*context = new Context(new ConcreteStrategySub());
12         context.contextInterface(5, 4);*/
13         context = new Context("sub");
14         context.contextInterface(5, 4);
15         
16         // 我想使用乘法算法
17         /*context = new Context(new ConcreteStrategyMul());
18         context.contextInterface(5, 4);*/
19         context = new Context("mul");
20         context.contextInterface(5, 4);
21     }
22 }

测试结果:

5 + 4 = 9;
5 - 4 = 1;
5 * 4 = 20;

 UML图:

猜你喜欢

转载自www.cnblogs.com/lixianyuan-org/p/9463153.html