KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Jt > JtSingleton


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 Singleton pattern.
11  */

12
13 public class JtSingleton extends JtObject {
14   private static Object JavaDoc instance;
15
16
17
18   public JtSingleton () {
19   }
20
21 /**
22   * Returns the unique class instance.
23   */

24
25   public static synchronized Object JavaDoc getInstance()
26   {
27
28     return instance;
29   }
30
31
32
33 /**
34   * Specifies the unique class instance.
35   */

36
37   public static synchronized void setInstance(Object JavaDoc newInstance)
38   {
39     if (instance == null)
40       instance = newInstance;
41
42   }
43
44
45   /**
46     * Process object messages.
47     * <ul>
48     * <li>JtREMOVE - Performs any housekeeping that may be required before
49     * this object is removed.
50     * </ul>
51     */

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

72
73      if (msgid.equals ("JtREMOVE")) {
74        return (super.processMessage (null));
75      }
76
77
78      handleError ("JtSingleton.processMessage: invalid message id:" + msgid);
79      return (null);
80
81   }
82
83  
84   /**
85    * Unit tests the messages processed by JtSingleton.
86    */

87
88   public static void main(String JavaDoc[] args) {
89
90     JtFactory main = new JtFactory ();
91     JtMessage msg, msg1;
92     Integer JavaDoc count;
93     JtSingleton singleton, singleton1;
94
95     System.out.println ("Creating an instance of a singleton ...");
96
97     // Create a JtSingleton instance
98

99     singleton = (JtSingleton) main.createObject ("Jt.JtSingleton", "singleton");
100
101
102     System.out.println ("Attempting to create a second instance of a singleton ...");
103
104     singleton1 = (JtSingleton) main.createObject ("Jt.JtSingleton", "singleton1");
105
106     main.removeObject ("singleton");
107
108
109   }
110
111 }
112
113
114
Popular Tags