单例设计模式
概念:
- 单例模式属于创建型模式,创建型模式的主要是“怎样创建出对象”
为什么使用创建型模式
- 将对象的创建于使用分离
- 降低系统的耦合度
- 使用者无需关注对象的创建细节
单例模式分为两种
- 懒汉式
public class Singleton {
//构造方法私有化
private Singleton() {
}
//防止指令重排,new Singleton底层的指令不是原子操作,底层被分为多条指令
//1、分配内存空间、2、初始化对象 3、设置instance指向分配的内存
private static volatile Singleton singleton=null;
//双重检查锁
public static Singleton getSingleton() {
if (singleton == null) {
//此时加锁,防止多线程共享临界资源
synchronized (Singleton.class) {
//如果同时有多个线程,同时进入,还需要进行一次判断
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
什么场景用到?
- 多线程中的线程池
- 数据库的连接池
- 系统环境信息
- 上下文(ServletContext)