享元模式运用共享技术有效地支持大量细粒度的对象,主要用于减少创建对象的数量,以减少内存占用和提高性能。尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象。
享元模式的优点是减少了对象的创建,降低了内存,提高效率;缺点是提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化。在系统中有大量相似对象或者需要缓冲池的场景可以使用享元模式。
public interface Shape {
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("Circle: Draw() [Color : " + color
+", x : " + x +", y :" + y +", radius :" + radius);
}
}
/**
* 享元模式,减少对象的创建,利用唯一标识码,
* 如果内存中已存在,则不进行创建
*/
import java.util.HashMap;
public class ShapeFactory {
private static final Map<String, Shape> circleMap = new HashMap<>();
public static Shape getShape(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 FlyweightInstance {
private static final String[] colors = {"Red", "Green", "Blue"};
public static void main(String[] args) {
for(int i=0;i<20;i++){
Circle circle = (Circle) ShapeFactory.getShape(getRandomColor());
circle.setX(getRandom());
circle.setY(getRandom());
circle.setRadius(100);
circle.draw();
}
}
private static int getRandom(){
return (int) (Math.random() * 100);
}
private static String getRandomColor(){
return colors[(int)(Math.random()) * colors.length];
}
}