饿汉式
public class Sington {
private static final Sington instance = new Sington();
private Sington() {}
public static Sington getInstance() {
return instance;
}
}
懒汉式
- 优点:支持延迟加载
- 缺点:加锁,并发度基本为1,频繁调用效率太低
public class Sington {
private static Sington instance;
private Sington() {}
public static synchronized Sington getInstance() {
if (instance==null) {
return new Sington();
}
return instance;
}
}
双重检测
public class Sington {
private static Sington instance;
private Sington() {}
public static Sington getInstance() {
if (instance==null) {
synchronized (Sington.class) {
if (instance==null) {
return new Sington();
}
}
}
return instance;
}
}
静态内部类
- 优点:静态内部类只有在调用的时候加载,由JVM保证唯一性和安全性
- 缺点:
public class Sington {
private Sington() {}
private static class SingtonInner {
private static final Sington instance = new Sington();
}
public static Sington getInstance() {
return SingtonInner.instance;
}
}
单例模式特点
- 私有化构造器,防止外部创建
- 私有化静态变量
- 公有的获取实例方法
网友评论