KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Jt > JtChainOfResponsibility


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

11
12
13 public class JtChainOfResponsibility extends JtObject {
14
15
16   private Object JavaDoc successor;
17
18   public JtChainOfResponsibility() {
19   }
20
21 /**
22   * Specifies the successor in the chain.
23   *
24   * @param successor successor
25   */

26
27   public void setSuccessor (Object JavaDoc successor) {
28      this.successor = successor;
29
30   }
31
32 /**
33   * Returns the successor in the chain.
34   */

35
36   public Object JavaDoc getSuccessor () {
37      return (successor);
38   }
39
40
41
42
43   /**
44     * Process object messages. If unable to process a particular message, forward it to the successor.
45     * @param event Jt Message
46     */

47
48   public Object JavaDoc processMessage (Object JavaDoc event) {
49
50    String JavaDoc msgid = null;
51    JtMessage e = (JtMessage) event;
52    Object JavaDoc content;
53
54  
55      if (e == null)
56     return null;
57
58      msgid = (String JavaDoc) e.getMsgId ();
59
60      if (msgid == null)
61     return null;
62
63      content = e.getMsgContent();
64
65
66      // Remove this object
67
if (msgid.equals ("JtREMOVE")) {
68        return (this);
69      }
70
71      // Unable to handle the request, let the successor process the request
72

73      if (successor == null) {
74        handleError
75         ("JtChainOfResposibility.processMessage: last in the chain was unable to process message ID:" + msgid);
76        return (null);
77      }
78
79      return (sendMessage (successor, event));
80
81
82   }
83
84   /**
85     * Unit Tests the messages processed by JtChainOfResposibilty.
86     */

87
88   public static void main(String JavaDoc[] args) {
89
90     JtObject main = new JtFactory ();
91     JtMessage msg;
92     Jt.examples.HelloWorld helloWorld;
93     JtChainOfResponsibility chain;
94
95
96
97     // Create an instance of JtChainOfResponsibilty
98

99     chain = (JtChainOfResponsibility)
100       main.createObject ("Jt.JtChainOfResponsibility",
101       "chain");
102
103
104     helloWorld = (Jt.examples.HelloWorld) main.createObject ("Jt.examples.HelloWorld",
105       "helloWorld");
106
107     main.setValue (chain, "successor", helloWorld);
108
109
110     msg = new JtMessage("JtHello");
111
112     // Send a message ("JtHello") to the chain
113

114     System.out.println (main.sendMessage (chain, msg));
115
116     main.removeObject ("chain");
117          
118
119   }
120
121 }
122
Free Books   Free Magazines  
Popular Tags