0%

flyweight

享元

定义

运用共享技术有效地支持大量细粒度的对象。

  • 谁和谁共享
  • 什么叫细粒度

核心思想

如果一个对象实例一经创建就不可变,那么反复创建相同的实例就没有必要,直接向调用方返回一个共享的实例就行

栗子

1
2
3
4
5
6
7
8
9
10
11
12
package eternal.fire;

public class Main {
public static void main(String[] args) {
String s1 = "Running constant pool";
String s2 = "Running constant pool";
System.out.println(s1 == s2);
Integer num1 = Integer.valueOf(101);
Integer num2 = Integer.valueOf(101);
System.out.println(num1 == num2);
}
}

String用字面量初始化的时候,会先看运行常量池里有没有已经存在的,如果有就返回一个引用,否则new一个放进运行常量池并返回引用

Integer.valueOf()方法和上面的类似,预先缓存了-128到127

Byte只有256个状态,如果用Byte.valueOf()返回的全是缓存

享用享元

因为这个模式是通过静态工厂方法实现的,所以创建变量的时候不要new而用静态工厂方法就可能享受到享元

设计享元模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package eternal.fire;


import java.util.HashMap;
import java.util.Map;

public class Student {
//cache
private static final Map<String, Student> cache = new HashMap<>();
private final int id;
private final String name;

public Student(int id, String name) {
this.id = id;
this.name = name;
}

//static factory method
public static Student createStudent(int id, String name) {
String key = id + name;
Student student = cache.get(key);
if (student == null) {
cache.put(id + name, new Student(id, name));
return cache.get(key);
} else {
return cache.get(key);
}
}

}

可以使用成熟的Cache库,如Guava的Cache