视频课程总结:
原视频课程链接:https://edu.youkuaiyun.com/course/play/19745/296864
1,什么是单例模式
单例模式就是采取一定的方法保证在整个软件系统中对某个类只能存在一个对象实例,并且该类只提供一个获取该对象实例的方法。
2,实现方式
饿汉式----静态常量
代码实现:
class Singleton{
private Singleton() {}
private final static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}
优点:
- 实现简单
- 类装载时完成实例化
- 避免线程同步问题
缺点:
- 在类装载时完成实例化,没有达到延迟加载效果
- 如果该实例从未使用过,会造成内存浪费
饿汉式----静态代码块
代码实现:
class Singleton{
private Singleton() {}
private static Singleton instance;
static {
instance = new Singleton();
}
public static Singleton getInstance() {
return instance;
}
}
优缺点同上
懒汉式----线程不安全
代码实现:
class Singleton{
private Singleton(){}
private static Singleton instance;
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
优点:
- 起到了延迟加载作用,只能在单线程下使用
缺点:
- 在多线程中可能会产生多个实例
注:在实际项目中不会使用这种方式
懒汉式----同步方法保证线程安全
代码实现:
class Singleton{
private Singleton() {}
private static Singleton instance;
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
优点:
- 解决了线程不安全问题
缺点:
- 锁的粒度太重, 效率低
注:在实际项目中不会使用这种方式
双重检查
代码实现:
class Singleton {
private Singleton() {}
private static volatile Singleton instance;
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
instance = new Singleton();
}
}
return instance;
}
}
优点:
- 多线程开发中常使用,可保证线程安全
- 实例化执行一次,后面再次访问直接return实例,避免反复方法同步
- 延迟加载,效率高
静态内部类
代码实现:
class Singleton{
private Singleton() {};
private static class SingletonInstance{
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.instance;
}
}
优点:
- 采用类装载机制,保证初始化实例时只有一个线程
- 外部类被装载时不会立即实例化,在用到时才实例化
- 类的静态属性只会在第一次加载类的时候初始化,jvm帮助保证线程安全,类进行初始化时别的线程无法进入
- 避免了线程不安全,利用静态内部类特点实现延迟加载
枚举
代码实现:
enum Singleton{
INSTANCE;
}
优点:
- 避免多线程同步问题
- 防止反序列化重新创建新的对象
总结:后面三种在实际项目中推荐使用,饿汉式可以使用,可能会造成内存资源浪费