解决的问题
当创建了大量对象,可能会因为使用内存过多而导致性能问题,可以考虑使用 Flyweight Pattern(轻量级模式)。
例如,开发一个地图软件,地图上面需要标注 100 个感兴趣的点:
Point
:
每个点中的 icon 是比较消耗内存的,假设一个 icon 占 20kb,那么 100 个点的 icon 大概要消耗 2M 的内存。
因为很多 icon 其实都是一样的,所以 Point 可以这样设计可以减少内存的消耗:
优化后的Point
:
其中,每种 icon(PointIcon
)只会创建一个实例,可以在不同Point
之间共享。这样设计,极大了减少了内存的消耗。这就是 Flyweight Pattern。
代码
PointType
:
package com.cong.designpattern.flyweight;
public enum PointType {
COFFEE,
STORE,
PARK,
}
PointIcon
:
package com.cong.designpattern.flyweight;
public class PointIcon {
public PointType type;
public byte[] icon;
public PointIcon(PointType type, byte[] icon) {
this.type = type;
this.icon = icon;
}
}
PointIconFactory
:
package com.cong.designpattern.flyweight;
import java.util.HashMap;
import java.util.Map;
public class PointIconFactory {
private static Map<PointType, PointIcon> icons = new HashMap<>();
public static PointIcon getIcon(PointType type) {
if (icons.containsKey(type)) return icons.get(type);
System.out.println("Create new PointIcon instance");
PointIcon icon = new PointIcon(type, null);
icons.put(type, icon);
return icon;
}
}
Point
:
package com.cong.designpattern.flyweight;
public class Point {
public int x;
public int y;
public PointIcon pointIcon;
public Point(int x, int y, PointIcon pointIcon) {
this.x = x;
this.y = y;
this.pointIcon = pointIcon;
}
}
Test code:
// 创建了3个Point,但是共享同一个PointIcon实例,节省了内存
Point p1 = new Point(1,1, PointIconFactory.getIcon(PointType.COFFEE));
Point p2 = new Point(2,2, PointIconFactory.getIcon(PointType.COFFEE));
Point p3 = new Point(3,3, PointIconFactory.getIcon(PointType.COFFEE));
网友评论