KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Jt > examples > patterns > Flyweight


1
2
3 package Jt.examples.patterns;
4 import java.util.*;
5 import java.lang.reflect.*;
6 import java.beans.*;
7 import java.io.*;
8 import Jt.*;
9
10
11 /**
12  * Demonstrates the use of Flyweight, Abstract Factory and State.
13  */

14
15 public class Flyweight extends JtFlyweight {
16
17
18
19   /**
20     * Process object messages.
21     * <ul>
22     * </ul>
23     * @param message Jt Message
24     */

25
26
27   public Object JavaDoc processMessage (Object JavaDoc message) {
28
29    String JavaDoc msgid = null;
30    JtMessage e = (JtMessage) message;
31    Object JavaDoc content;
32    Object JavaDoc data;
33    JtMessage tmp;
34    JtInterface aux, aux1;
35    
36
37
38      if (e == null)
39     return null;
40
41      msgid = (String JavaDoc) e.getMsgId ();
42
43      if (msgid == null)
44     return null;
45
46      content = e.getMsgContent();
47      data = e.getMsgData ();
48
49      // Remove this object
50
if (msgid.equals ("JtREMOVE")) {
51        return (this);
52      }
53
54       
55      return (super.processMessage (message));
56      
57   }
58
59  
60   /**
61    * Main program. It
62    */

63
64   public static void main(String JavaDoc[] args) {
65
66     JtObject main = new JtFactory ();
67     SwitchFactory switchFactory;
68     JtMessage msg;
69     Vector switches;
70     int i;
71     JtState myswitch;
72
73
74     JtFlyweight flyweightp;
75
76     // Create instances of JtFlyweight and SwitchFactory
77

78     flyweightp = (JtFlyweight) main.createObject ("Jt.JtFlyweight", "flyweight");
79     switchFactory = (SwitchFactory) main.createObject
80       ("Jt.examples.patterns.SwitchFactory", "switchFactory");
81     main.setValue (flyweightp, "factory", switchFactory);
82
83
84     // Manages and shares 100 flyweights (switches). Actually only two State
85
// instances are created.
86

87     switches = new Vector ();
88
89     msg = new JtMessage ("JtGET_FLYWEIGHT");
90
91
92     System.out.println ("Requesting and sharing 100 flyweights (switches) ...");
93
94     for (i = 0; i <= 100; i++) {
95       if (i % 2 == 0)
96         msg.setMsgData ("On");
97       else
98         msg.setMsgData ("Off");
99       myswitch = (JtState) main.sendMessage (flyweightp, msg);
100       switches.addElement (myswitch);
101     }
102
103     // Display the switches
104

105
106     System.out.println ("Displaying the state of the 100 switches ...");
107
108     for (i = 0; i <= 100; i++) {
109       myswitch = (JtState) switches.elementAt (i);
110       System.out.println ("Switch" + i + ":"
111        + main.sendMessage (myswitch, new JtMessage ("JtSWITCH_VALUE")));
112     }
113
114
115     main.removeObject ("flyweight");
116
117
118   }
119
120 }
121
122
123
Popular Tags