|
Design Pattern |
|
FlyweightFactory.java
class FlyweightFactory {
private HashMap lstFlyweight;
private static FlyweightFactory factory = new
FlyweightFactory();
private FlyweightFactory() {
lstFlyweight = new HashMap();
}
public synchronized FlyweightIntr
getFlyweight(String divisionName) {
if (lstFlyweight.get(divisionName) == null) {
FlyweightIntr fw = new
Flyweight(divisionName);
lstFlyweight.put(divisionName, fw);
return fw;
} else {
return
(FlyweightIntr)lstFlyweight.get(divisionName);
}}
public static FlyweightFactory getInstance() {
return factory;
}
The client accesses this factory of
employees. Every time, the client wants the information,
which is accessed through this Factory
class. The specifications are passed through the
method parameters and new employee information is returned.
Flyweight.java
//Inner flyweight class
private class Flyweight implements
FlyweightIntr {
private String name;
private String addr;
private void setValues(String name, String
addr) {
this.name = name;
this.addr = addr;
}
|
|
private Flyweight(String division) {
if (division.equals(“North”)) {
setValues(“soniya”, “addr1”);
}
if (division.equals(“South”)) {
setValues(“rahul”, “addr2”);
}
if (division.equals(“East”)) {
setValues(“Aqil”, “addr3”);
}
}
public String getName() {
return company;
}
public String getAddress() {
return address;
}
}// end of Flyweight
}// end of FlyweightFactory
class VCard {
String name;
String title;
FlyweightIntr objFW;
public VCard(String n, FlyweightIntr fw) {
name = n;
objFW = fw;
}
public void print() {
System.out.println(name);
System.out.println(name objFW.getAddress()
);
}
}
The other important class is Flyweight. This gets constructed depending on the parameters
passed to the method getName() and getAddr() of class
FlyweightFactory.
This class has methods getters and setters for
information. In each of the instances of
the employees, we can pass the values as method parameters. Hence, we can see that by using the flyweight pattern, we can reduce the instances of the class. |
|
Nov 2007 | Java Jazz Up | 42 |
|
|
|
View All Topics |
All Pages of this Issue |
Pages:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53 ,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63 ,
64,
65 ,
66 ,
67 ,
68 ,
69 Download PDF |
|
|
|
|
|
|
|
|
|