-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDS11_Flyweight.java
More file actions
65 lines (46 loc) · 1.46 KB
/
DS11_Flyweight.java
File metadata and controls
65 lines (46 loc) · 1.46 KB
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
import java.util.*;
//这个例子不太好
//Flyweight
interface Flyweight {
void action(int arg);
}
//ConcreteFlyweight
class FlyweightImpl implements Flyweight {
public void action(int arg) {
// TODO Auto-generated method stub
System.out.println("参数值:" + arg);
}
}
//FlyweightFactory
class FlyweightFactory {
private static Map flyweights = new HashMap();
public FlyweightFactory(String arg) {
flyweights.put(arg, new FlyweightImpl());
}
public static Flyweight getFlyweight(String key) {
if (flyweights.get(key) == null) {
flyweights.put(key, new FlyweightImpl());
}
return (Flyweight)flyweights.get(key);
}
public static int getSize() {
return flyweights.size();
}
}
//Test
public class DS11_Flyweight{
public static void main(String[] args) {
// TODO Auto-generated method stub
Flyweight fly1 = FlyweightFactory.getFlyweight("a");
fly1.action(1);
Flyweight fly2 = FlyweightFactory.getFlyweight("a");
System.out.println(fly1 == fly2);
Flyweight fly3 = FlyweightFactory.getFlyweight("b");
fly3.action(2);
Flyweight fly4 = FlyweightFactory.getFlyweight("c");
fly4.action(3);
Flyweight fly5 = FlyweightFactory.getFlyweight("d");
fly4.action(4);
System.out.println(FlyweightFactory.getSize());
}
}