享元模式

对象复用

场景


对象广泛使用并且可以复用

代码


Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Color {
private Map<String, Color> map = new HashMap<>();

private int r;
private int g;
private int b;

public Color(int r, int g, int b){
this.r = r;
this.g = g;
this.b = b;
}

public static Color getColor(int r, int g, int b) {
String encode = "#"+Integer.toHexString(r)+Integer.toHexString(g)+Integer.toHexString(b);
if(!map.contains(encode)) {
map.put(new Color(r,g,b));
}
return map.get(encode);
}
}

优缺点


  • 降低内存消耗
  • 避免重复创建

注意


对象被共享,注意对象状态的维护以及线程安全问题

应用

java.lang.String的intern方法
java.lang.Integer的valueOf方法