【設計模式】享元模式
阿新 • • 發佈:2018-12-25
模式定義
享元模式主要用於減少建立物件的數量,以減少記憶體佔用和提高效能。
下圖是該模式的類圖:
一個生動的例子
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) ;
}
}
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;
}
}
客戶端:
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();
}
}
private static String getRandomColor() {
return CORLORS[(int) (Math.random() * length)];
}
private static int getRandomX() {
return (int) (Math.random() * 100);
}
private static int getRandomY() {
return (int) (Math.random() * 100);
}
}