Open lveay2 opened 5 years ago
Singleton
Double checked locking pattern
public class Singleton {
private volatile static Singleton instance; //声明成 volatile
private Singleton (){}
public static Singleton getSingleton() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Static final field
public class Singleton{
private static final Singleton instance = new Singleton(); //类加载时就初始化
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
Static nested class
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Enum
public enum EasySingleton{
INSTANCE;
}
Reference: http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/
Enum Singleton
public enum Singleton {
INSTANCE;
// A private constructor is hidden here
private Singleton () {}
}
// Define what the singleton must do.
public interface MySingleton {
public void doSomething();
}
private enum Singleton implements MySingleton {
/**
* The one and only instance of the singleton.
*
* By definition as an enum there MUST be only one of these and it is inherently thread-safe.
*/
INSTANCE {
@Override
public void doSomething() {
// What it does.
}
};
}
public static MySingleton getInstance() {
return Singleton.INSTANCE;
}
Reference: https://www.jianshu.com/p/4e8ca4e2af6c https://stackoverflow.com/questions/26285520/implementing-singleton-with-an-enum-in-java https://stackoverflow.com/questions/23721115/singleton-pattern-using-enum-version