多例模式
public class Multition {
/**
* 多例模式:
* Ensure a class only has limited number of instances, and provide a global point of access to them。
* 确保一个类具有有限个实例,并提供一个全局访问点来访问他们。
*/
@Test
public void all() {
final MultionLight l1 = MultionLight.get(Light.RED);
final MultionLight l2 = MultionLight.get(Light.RED);
assertEquals(l1, l2);
}
}
enum Light {
RED, GREEN, YELLOW;
}
@Data
class MultionLight {
private static final ConcurrentMap<Light, MultionLight> INSTANCES;
private final Light light;
private MultionLight(Light light) {
this.light = light;
}
static {
INSTANCES = Arrays.stream(Light.values()).
collect(Collectors.toConcurrentMap(val -> val, val -> new MultionLight(val)));
}
public static final MultionLight get(Light light) {
return INSTANCES.get(light);
}
}