使用枚举实现单例模式

前言

单例模式的实现方式有多种,从最基础的非LazyLoad的懒汉式,到LazyLoad但需要双重检查的饿汉式,再到比较简单实现LazyLoad的静态内部类方式,均可实现单例模式。(忘了的可以查查资料:D 友情链接:http://blog.51cto.com/devbean/203501)不过使用枚举实现单例模式,可称之为实现单例模式最简单的方法。

实现

public enum MySingleton {
    INSTANCE;   

    // all the methods you want
    private String hello() {
        System.out.println("Hello, world!");
    }
}

需要使用单例时,直接MySingleton.INSTANCE即可得到枚举对象。调用对象的方法,如MySingleton.INSTANCE.hello(),以实现需要的功能。

说明

为什么枚举类能这么简单实现单例?回顾一下单例的两个经典模式所需的条件:

  • 懒汉式:private构造函数,提前new,需要时直接return;
  • 饿汉式:private构造函数,需要时再new,导致了double check;

再看枚举,符合构造函数为private,且在首次调用的时候使用构造函数构造枚举对象。因此枚举完全可以胜任单例的工作,而且是LazyLoad,并且不需要双重检查。

https://stackoverflow.com/questions/26285520/implementing-singleton-with-an-enum-in-java

Q:
I have read that it is possible to implement Singleton in Java using an Enum such as:

public enum MySingleton {
INSTANCE;
}
But, how does the above work? Specifically, an Object has to be instantiated. Here, how is MySingleton being instantiated? Who is doing new MySingleton()?

A:
This,

public enum MySingleton {
INSTANCE;
}
has an implicit empty constructor. Let’s be explicit instead,

public enum MySingleton {
INSTANCE;
private MySingleton() {
System.out.println(“Here”);
}
}
If you then added another class with a main() method like

public static void main(String[] args) {
System.out.println(MySingleton.INSTANCE);
}
You would see

Here
INSTANCE
enum fields are compile time constants, but they are instances of their enum type. And, they’re constructed when the enum type is referenced for the first time.

猜你喜欢

转载自blog.csdn.net/puppylpg/article/details/77044813