- 饿汉式(静态常量或静态代码块)
public class StaticSingleton {
private static StaticSingleton singleton = new StaticSingleton();
private StaticSingleton(){
}
public static StaticSingleton getSingleton(){
return singleton;
}
}
- 懒汉式(线程安全,同步方法)
public class SynSingleton {
private static SynSingleton singleton;
private SynSingleton() {
}
public static synchronized SynSingleton getSingleton() {
if (singleton == null) {
singleton = new SynSingleton();
}
return singleton;
}
}
- 懒汉式(线程安全,双重检查,同步代码块)
public class DoubleCheckSingleton {
private static volatile DoubleCheckSingleton singleton;
private DoubleCheckSingleton() {
}
public static DoubleCheckSingleton getSingleton() {
if (singleton == null) {
synchronized (DoubleCheckSingleton.class) {
if (singleton == null) {
singleton = new DoubleCheckSingleton();
}
}
}
return singleton;
}
}
- 静态内部类
public class InnerClassSingleton {
private static InnerClassSingleton singleton;
private InnerClassSingleton() {
}
private static class SingletonInstance {
private static InnerClassSingleton instance = new InnerClassSingleton();
}
public static InnerClassSingleton getInstance() {
return SingletonInstance.instance;
}
}
网友评论