享元模式主要解决减少创建对象数量,减少内存占用,节约资源,提高性能。
享元模式先从已有对象中匹配,如果有则使用已有对象,没有才会创建新的对象,
这样可以实现对象的复用,减少不必要的创建。
基本思路:使用HashMap将对象存储起来,后续使用时在HashMap中寻找,如果有则使用已有对象,
如果没有则创建对象,并将其放在HashMap中。
假设现在需要绘制圆形,圆形有几个参数,圆心位置,半径,颜色。
如果每次绘制圆,圆心,半径每次都可能不一样。
但是,不同位置,不同半径的圆的颜色可能是相同的。
此时我们就可以通过颜色来区分圆。
例如一个圆半径为3,一个圆半径为10,但都是红色的圆,
我们就只需要创建一个红色圆对象,为其设置半径和位置即可,不必创建两个对象。
Shape
public interface Shape {
void draw();
}
Circle, 实现Shape接口,主要属性,x,y圆心坐标,radius半径,color颜色。
初始化对象时,构造函数设Color
public class Circle implements Shape{
private String color;
private int x;
private int y;
private int radius;
public String getColor() {
return color;
}
public Circle(String color) {
super();
this.color = color;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("Circle: Draw() [Color : " + color
+", x : " + x +", y :" + y +", radius :" + radius + "]");
}
}
ShapeFactory
import java.util.HashMap;
import java.util.Map;
public class ShapeFactory {
private static Map<String,Shape> hMap = new HashMap<String,Shape>();
public static Circle getCircle(String color) {
Circle circle = (Circle)hMap.get(color);//首先通过颜色获取已存在的圆
if(circle == null) { //如果没有则为其创建,并将其放入hMap中
circle = new Circle(color);
hMap.put(color, circle);//每次创建对象则输出创建信息
System.out.println("----create circle:" + color + "----");
}
return circle;
}
}
Main
public class Main {
private static String[] colors = {"red","green","bule"};
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
//从工厂中获取圆对象,
//如果有则直接获取并返回
//如果没有则创建对象,并将其放入HashMap中,并返回创建对象
Circle circle = ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandom());//随机指定圆心位置
circle.setY(getRandom());
circle.setRadius(getRandom());//随机指定半径
circle.draw();
}
}
//生成随机颜色
public static String getRandomColor() {
return colors[((int)(Math.random() * 10)) % colors.length];
}
//生成随机数
public static int getRandom() {
return (int)(Math.random() * 100);
}
}
运行结果:----create circle:red---- Circle: Draw() [Color : red, x : 57, y :38, radius :59] Circle: Draw() [Color : red, x : 0, y :77, radius :25] ----create circle:green---- Circle: Draw() [Color : green, x : 29, y :77, radius :52] Circle: Draw() [Color : red, x : 0, y :88, radius :49] Circle: Draw() [Color : green, x : 7, y :11, radius :52] Circle: Draw() [Color : red, x : 20, y :7, radius :51] Circle: Draw() [Color : green, x : 8, y :18, radius :94] ----create circle:bule---- Circle: Draw() [Color : bule, x : 93, y :25, radius :64] Circle: Draw() [Color : red, x : 76, y :75, radius :47] Circle: Draw() [Color : red, x : 29, y :85, radius :96]
观察运行结果可以看到,绘制的圆有10个,但是只创建了3个对象。
这样可以大大减少对象数量。
参考资料:
https://www.runoob.com/design-pattern/flyweight-pattern.html
来源:https://www.cnblogs.com/huang-changfan/p/10962556.html