享元模式

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
70
71
72
73
74
75
76
import java.util.HashMap;

interface Shape {
void draw();
}

class Circle implements Shape {
String color;
int x;
int y;
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);
}
}

class ShapeFactory {
private static final HashMap<String, Shape> circleMap = new HashMap<>();

public static Shape getCircle(String color) {
Circle circle = (Circle) circleMap.get(color);

if (circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("Creating circle of color : " + color);
}
return circle;
}
}

public class FlyweightPatternDemo {
private static final String[] colors = {"Red", "Green", "Blue", "White", "Black"};

public static void main(String[] args) {
for (int i = 0; i < 20; ++i) {
Circle circle =
(Circle) ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
circle.draw();
}
}

private static String getRandomColor() {
return colors[(int) (Math.random() * colors.length)];
}

private static int getRandomX() {
return (int) (Math.random() * 100);
}

private static int getRandomY() {
return (int) (Math.random() * 100);
}
}

享元模式
https://wangqian0306.github.io/2021/design-flyweight-pattern/
作者
WangQian
发布于
2021年7月21日
许可协议