共享物件,用來儘可能減少記憶體使用量以及分享資訊給儘可能多的相似物件。
public interface Shape {
public void draw();
}
public 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("圓形[顏色 : " + color + ", x : " + x + ", y : " + y + ", radius : " + radius + " ]");
}
}
public class ShapeFactory {
private static final HashMap<String, Shape> circleMap = new HashMap();
public static Shape getCircle(String color) {
Circle circle = (Circle) circleMap.get(color);
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("建立一個圓形顏色為 : " + 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 < 5; ++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);
}
}
建立一個圓形顏色為 : Green
圓形[顏色 : Green, x : 29, y : 97, radius : 100 ]
建立一個圓形顏色為 : Red
圓形[顏色 : Red, x : 52, y : 98, radius : 100 ]
建立一個圓形顏色為 : Red
圓形[顏色 : Red, x : 19, y : 80, radius : 100 ]
建立一個圓形顏色為 : White
圓形[顏色 : White, x : 3, y : 0, radius : 100 ]
建立一個圓形顏色為 : Red
圓形[顏色 : Red, x : 81, y : 39, radius : 100 ]