多例模式【其他模式】

多例模式

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);
    }
}

posted on 2019-01-03 21:09  竺旭东  阅读(89)  评论(0编辑  收藏  举报

导航