设计模式之二 策略模式


 1 /**
2 * 文件名:strategy.java
3 *
4 * 版本信息:
5 * 日期:2011-12-12
6 * Copyright 陈亚坤 Corporation 2011
7 * 版权所有
8 *
9 */
10 package byME;
11
12 /**
13 *
14 * 项目名称:Design Pattern 类名称:strategy 类描述: 创建人:chenyakun 创建时间:2011-12-12
15 * 下午05:02:31 修改人:chenyakun 修改时间:2011-12-12 下午05:02:31 修改备注:
16 *
17 * @version
18 *
19 */
20 abstract class Strategy {
21
22 // 算法方法
23 public abstract void AlgorithmInterface();
24
25 }
26
27 // ConcreteStrategy,封装了具体的算法或行为,继承了Strategy
28 class ConcreteStrategyA extends Strategy {
29
30 /*
31 * (non-Javadoc)
32 *
33 * @see strategy.Strategy#AlgorithmInterface()
34 */
35 @Override
36 public void AlgorithmInterface() {
37 System.out.println("ConcreteStrategyA.AlgorithmInterface()");
38 }
39
40 }
41
42 // ConcreteStrategy,封装了具体的算法或行为,继承了Strategy
43 class ConcreteStrategyB extends Strategy {
44
45 /*
46 * (non-Javadoc)
47 *
48 * @see strategy.Strategy#AlgorithmInterface()
49 */
50 @Override
51 public void AlgorithmInterface() {
52 System.out.println("ConcreteStrategyB.AlgorithmInterface()");
53 }
54
55 }
56
57 // Context,用一个ConcreteStategy 来配置,维护strategy对象的引用
58 class Context {
59
60 Strategy strategy;
61
62 public Context(Strategy strategy) {
63 this.strategy = strategy;
64 }
65
66 /*
67 * 根据具体的策略对象,调用其算法的方法。
68 */
69 public void ConcreteInterface() {
70 strategy.AlgorithmInterface();
71 }
72 }
73
74 // 客户端实现
75 class Client {
76 public static void main() {
77 Context context;
78
79 // 调用策略StrategyA
80 context = new Context(new ConcreteStrategyA());
81 context.ConcreteInterface();
82
83 // 调用策略StrategyB
84 context = new Context(new ConcreteStrategyB());
85 context.ConcreteInterface();
86 }
87
88 }
89
90 /*
91 * 如果需要增加新的策略,只需设计新的继承Strategy,改写AlgorithmInterface方法,封装新的算法即可。 不需要改动客户端。
92 */
原文地址:https://www.cnblogs.com/yakun/p/2285231.html