首页 > 代码库 > 设计模式之单例模式
设计模式之单例模式
/**
* 贪婪模式(EAGER)
*/
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
// DO NOTHING
}
public static final Singleton getInstance() {
return INSTANCE;
}
}
///////////////////////////////////////////////////////////////
/**
* 懒汉模式(LAZY)
*/
public class Singleton {
private volatile static Singleton INSTANCE = null;
private Singleton() {
// DO NOTHING
}
public static Singleton getInstance() {
if (null == INSTANCE) {
synchronized (Singleton.class) {
INSTANCE = new Singleton();
}
}
return INSTANCE;
}
}
///////////////////////////////////////////////////////////
/**
* 嵌套类
*/
public class Singleton {
private Singleton() {
// DO NOTHING
}
public static final Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
private static final class SingletonHelper {
private static final Singleton INSTANCE = new Singleton();
}
}
/////////////////////////////////////////////////////////////
/**
* 枚举
*/
设计模式之单例模式