enum 实现单例

需要单例的类 SinletonObject

@AllArgsConstructor
public class SinletonObject {
    private Integer id;
    private String desc;
}

枚举类实现单例

public enum SingletonEnum {
    INSTANCE;
    private SinletonObject instance;

    SingletonEnum(){
        System.out.println(" -new instance --");
        instance = new SinletonObject(1,"hello");
    }
    public SinletonObject getInstance() {
        return instance;
    }
}

测试下

public class SingletonTest {
    public static void main(String[] args) {
        System.out.println(SingletonEnum.INSTANCE.getInstance());
        System.out.println(SingletonEnum.INSTANCE.getInstance());
    }
}

运行结果,只初始化了一次

-new instance --
com.river.face.Singleton.SinletonObject@65b54208
com.river.face.Singleton.SinletonObject@65b54208

你可能感兴趣的:(enum 实现单例)