/**
* Created by wangxiaoma on 2017/3/3.
*/
// 内部类-线程安全的
class InnerSingleton {
private static class SingletonFactory {
private static final InnerSingleton INSTANCE = new InnerSingleton();
}
private InnerSingleton() {
}
public static final InnerSingleton getInstance() {
return SingletonFactory.INSTANCE;
}
}
// 懒汉式-线程安全的
class LHSingleton {
private static LHSingleton INSTANCE = new LHSingleton();
private LHSingleton() {
}
public static LHSingleton getInstance() {
return INSTANCE;
}
}
// 双重校验锁-线程安全的
class JYSSingleton {
private volatile static JYSSingleton INSTANCE;
private JYSSingleton() {
}
public static JYSSingleton getInstance() {
if (INSTANCE == null) {
synchronized (JYSSingleton.class) {
if (INSTANCE == null) {
INSTANCE = new JYSSingleton();
}
}
}
return INSTANCE;
}
}
// 枚举-线程安全
enum ESingleton {
E_SINGLETON;
}
前3种实现方式是项目中使用频率最高的,最后一种枚举实现,如果对枚举有深入了解,那么也可以尝试使用。枚举这朵奇葩在业界一直被认为:会用就用,不会用,就不要去学怎么用了,因为有句话叫:条条大路通罗马。