梗概
- 对于某个类,其只能创建一个实例
详解
适用范围
- 防止一个全局使用的类频繁地创建与销毁。
- 当您想控制实例数目,节省系统资源的时候。
使用场景
- child::Nodejs
- 单线程,污染比较少
JAVA实现方式
这里只介绍常用推荐的
饿汉式
适用范围:
优点:
缺点
- 不支持懒初始化
代码
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
内部静态类
适用范围
优点
代码
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}