KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Jt > JtStrategy


1
2
3 package Jt;
4 import java.util.*;
5 import java.lang.reflect.*;
6 import java.beans.*;
7 import java.io.*;
8
9 /**
10  * Jt implementation of the Strategy pattern.
11  */

12
13 public class JtStrategy extends JtObject {
14
15
16   private Object JavaDoc concreteStrategy = null; // Concrete Strategy object
17

18
19   public JtStrategy () {
20   }
21
22
23
24 /**
25   * Specifies the reference to the concrete strategy.
26   */

27
28
29   public void setConcreteStrategy (Object JavaDoc concreteStrategy) {
30      this.concreteStrategy = concreteStrategy;
31   }
32
33
34 /**
35   * Returns the reference to the concrete strategy.
36   */

37
38   public Object JavaDoc getConcreteStrategy () {
39      return (concreteStrategy);
40   }
41
42
43
44
45
46
47   /**
48     * Process object messages.
49     * <ul>
50     * <li>JtREMOVE - Performs any housekeeping that may be needed before the object
51     * is removed.
52     * </ul>
53     */

54
55   public Object JavaDoc processMessage (Object JavaDoc event) {
56
57    String JavaDoc msgid = null;
58    JtMessage e = (JtMessage) event;
59    Object JavaDoc content;
60    Object JavaDoc data;
61
62
63      if (e == null)
64     return null;
65
66      msgid = (String JavaDoc) e.getMsgId ();
67
68      if (msgid == null)
69     return null;
70
71      content = e.getMsgContent();
72      //data = e.getMsgData ();
73

74
75      if (msgid.equals ("JtREMOVE")) {
76        return (null);
77      }
78
79      // Let the concrete strategy object handle the message
80

81      if (concreteStrategy == null) {
82        handleError ("processMessage: concreteStrategy attribute must be set");
83        return (null);
84      }
85
86      return (((JtObject) concreteStrategy).processMessage (event));
87
88
89   }
90
91  
92   /**
93    * Unit tests the messages processed by JtStrategy.
94    */

95
96   public static void main(String JavaDoc[] args) {
97
98     JtFactory factory = new JtFactory ();
99     JtStrategy strategy;
100     JtObject concreteStrategy;
101
102     // Create an instance of JtStrategy
103

104     strategy = (JtStrategy) factory.createObject ("Jt.JtStrategy", "strategy");
105
106     // Specify the concrete strategy to be executed
107

108     concreteStrategy = (JtObject) factory.createObject ("Jt.JtEcho", "concreteStrategy");
109     factory.setValue (strategy, "concreteStrategy", concreteStrategy);
110
111     
112     factory.sendMessage (strategy, new JtMessage ("JtEXECUTE_STRATEGY"));
113
114     factory.removeObject ("strategy");
115
116
117   }
118
119 }
120
121
122
Popular Tags