享元模式分析
主要用於減少創建對象的數量,以減少內存佔用和提高性能。嘗試重用現有的同類對象,如果未找到匹配的對象,則創建新對象。
代碼示例
//享元模式
public class FlyweightModule {
public interface Shape {
void draw();
}
static 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("Circle: Draw() [Color : " + color
+", x : " + x +", y :" + y +", radius :" + radius);
}
}
}
class ShapeFactory {
private static final HashMap<String, FlyweightModule.Shape> circleMap = new HashMap<String, FlyweightModule.Shape>();
public static FlyweightModule.Shape getCircle(String color) {
FlyweightModule.Circle circle = (FlyweightModule.Circle)circleMap.get(color);
if(circle == null) {
circle = new FlyweightModule.Circle(color);
circleMap.put(color, circle);
System.out.println("Creating circle of color : " + color);
}
return circle;
}
private static final String colors[] =
{ "Red", "Green", "Blue", "White", "Black" };
public static void main(String[] args) {
for(int i=0; i < 20; ++i) {
FlyweightModule.Circle circle =
(FlyweightModule.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);
}
}
優點:
- 大大減少對象的創建,降低系統的內存,使效率提高。
缺點:
- 提高了系統的複雜度,需要分離出外部狀態和內部狀態,而且外部狀態具有固有化的性質,不應該隨着內部狀態的變化而變化,否則會造成系統的混亂。