• 单例模式是什么
  • 单例模式是为了解决什么问题
  • 怎么使用单例模式

单例模式是什么

用来创建独一无二的,只能有一个实例的对象的入场券。确保一个类只有一个实例,并提供一个全局访问点。

解决什么问题

1. 避免频繁地创建和销毁对象对资源的浪费,如:线程池、网络请求、数据库等。

2. 需要使用的对象有且只有一个。如:缓存、注册表、日志对象等。

  • 优点: 可以减少系统内存开支,减少性能开销,避免对资源的多重占用,同时操作。
  • 缺点:扩展困难,测试困难,违背“单一原则”

怎么使用单例模式

1. 恶汉模式

1
2
3
4
5
6
7
8
//属于急切加载
public class Singleton{
private static final Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance(){
return instance;
}
}

2. 懒汉模式(同步方法)

1
2
3
4
5
6
7
8
9
10
11
//懒加载 由于每次都需要同步,存在性能问题
public class Singleton{
private static final Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}

3. 双重检查锁定(DCL)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 懒加载 JDK >= 1.5
public class Singleton{
private static volatile Singleton instance = null;
private Singleton (){}
public static Singleton getInstance(){
//避免不必要的同步
if(instance == null){
//仅同步实例化的代码块
synchronized(Singleton.class){
//保证线程安全
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}

4. 静态内部类单例

1
2
3
4
5
6
7
8
9
10
11
// 懒加载 利用 classloder 的机制保证初始化 instance 只有一个
public class Singleton{
private Singleton (){}
public static final Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
//内部类
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
}
文章来源: