1. 程式人生 > >多例模式【其他模式】

多例模式【其他模式】

多例模式

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