Flyweight抽象类:
public interface Shape {
void draw();
}
Flyweight具体类:
class Circle implements Shape {
private String color;
private int x;
private int y;
private int radius;
public Circle(String color) {
this.color = color;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius);
}
}
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
FlyweightFactory类:
public class ShapeFactory {
private static final Map<String, Circle> CIRCLE_MAP = new HashMap<>();
public static Circle getCircle(String color) {
Circle circle = CIRCLE_MAP.get(color);
if (circle == null) {
circle = new Circle(color);
CIRCLE_MAP.put(color, circle);
System.out.println("Creating circle of color : " + color);
}
return circle;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
客户端:
public class FlyweightTest {
private static final String CORLORS[] = { "Red", "Green", "Blue", "White", "Black" };
private static int length = CORLORS.length;
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
Circle circle = ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
circle.draw();
}
}