整明白枚举单例模式

来源:互联网 发布:通信达交易软件 编辑:程序博客网 时间:2024/06/07 01:11

今天看到单例模式的各种写法,其中有个使用枚举实现单例模式的例子,大概是这样的:

public enum Singleton {    Instance;    public void anyMethod(){}}

看完就蒙圈了,完全不知道怎么回事,这就写完了?怎么用啊?,然后各种百度,网上的例子基本分为两种,第一种就是上面写的那样,第二种大概是这样的:

public enum Singleton {    Instance;    private SingletonEntity se;    public SingletonEntity getInstance() {        se = new SingletonEntity();        return se;    }}

其中SingletonEntity是需要使用单例的类,然后网上说是这么使用的:

SingletonEntity se = Singleton.Instance.getInstance();

看完更蒙圈了,既然可以在Singleton中new单例对象,那在别的地方不是也可以吗?那哪都可以new单例对象,还叫单例对象么?

蒙圈中突然想到,为什么用枚举的方式来实现单例模式?因为枚举的构造方式和单例模式很像(构造方法私有化),而且不用考虑序列化等问题。那么也就是说枚举类本身很符合单例模式,也就是说上面代码中的Singleton才是我们需要的单例。
简单写个例子:

// 单例public enum BeanContext {    Instance;    private BeanContext() {        System.out.println("init");    }    public void print() {        System.out.println("ffffffffffff");    }//测试public static void main(String[] args) {        BeanContext b1 = BeanContext.Instance;        b1.print();        BeanContext b2 = BeanContext.Instance;        b2.print();        BeanContext b3 = BeanContext.Instance;        b3.print();        BeanContext b4 = BeanContext.Instance;        b4.print();    }

打印结果中显示只打印了一次 “init”,说明只初始化了一次该对象;

回头想想,起始第一段代码已经说明了该枚举类本身就实现了单例,但是对枚举使用的比较少,没想明白是怎么回事。

原创粉丝点击