1、简介
享元模式(Flyweight Pattern),主要用于减少对象的穿件,减少内存的占用以提高程序性能。
尝试重用现有对象,如果未找到匹配的对象,再去新建对象。
核心代码:
让Hashmap缓存这些对象
优点:
大大减少了对象的创建,降低系统内存,提高运行效率
缺点:
提高了系统的复杂度,需要分离为内部状态和外部状态,而且外部状态具有固有化的性质,不应该根据内部状态的变化而变化,否则会造成系统混乱。
注意事项:
- 必须区分外部状态和内部状态
- 必须增加一个工厂对象加以控制
2、使用
// 形状接口
public interface Shape {
void draw();
}
// 形状类
public class Cricle implements Shape{
private String color;
private int x;
private int y;
private int radius;
@Override
public void draw() {
System.out.println("draw Cricle [color=" + color + ", x=" + x + ", y=" + y + ", radius=" + radius + "]");
}
@Override
public String toString() {
return "Cricle [color=" + color + ", x=" + x + ", y=" + y + ", radius=" + radius + "]";
}
public String getColor() {
return color;
}
public void setColor(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;
}
}
// 形状工厂
public class CircleFactory {
private static final HashMap<String, Shape> circles = new HashMap<>();
public static Shape getCircle(String color) {
Cricle cricle = (Cricle) circles.get(color);
if(cricle == null) {
cricle = new Cricle();
cricle.setColor(color);
System.err.println("Create new color"+ color);
circles.put(color, cricle);
}
return cricle;
}
}
// Test
private static final String[] colors = {"Red", "Yello", "Green", "White", "Black"};
for(int i=0;i<16;i++) {
String color = colors[(int)(Math.random()*colors.length)];
Cricle circlo = (Cricle) CircleFactory.getCircle(color);
circlo.setRadius(100);
circlo.setX((int)Math.random()*100);
circlo.setY((int)Math.random()*100);
circlo.draw();
}