单例模式的实现方式

视频课程总结:
原视频课程链接: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;
	}
}

优点:

  1. 实现简单
  2. 类装载时完成实例化
  3. 避免线程同步问题

缺点:

  1. 在类装载时完成实例化,没有达到延迟加载效果
  2. 如果该实例从未使用过,会造成内存浪费

饿汉式----静态代码块
代码实现:

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;
	}
}

优点:

  1. 起到了延迟加载作用,只能在单线程下使用

缺点:

  1. 在多线程中可能会产生多个实例

注:在实际项目中不会使用这种方式

懒汉式----同步方法保证线程安全
代码实现:

class Singleton{
	private Singleton() {}
	private static Singleton instance;
	public static synchronized Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

优点:

  1. 解决了线程不安全问题

缺点:

  1. 锁的粒度太重, 效率低

注:在实际项目中不会使用这种方式

双重检查
代码实现:

class Singleton {
	private Singleton() {}
	private static volatile Singleton instance;
	public static Singleton getInstance() {
		if(instance == null) {
			synchronized (Singleton.class) {
				instance = new Singleton();
			}
		}
		return instance;
	}
}

优点:

  1. 多线程开发中常使用,可保证线程安全
  2. 实例化执行一次,后面再次访问直接return实例,避免反复方法同步
  3. 延迟加载,效率高

静态内部类
代码实现:

class Singleton{
	private Singleton() {};
	private static class SingletonInstance{
		private static final Singleton instance = new Singleton();
	} 
	public static Singleton getInstance() {
		return SingletonInstance.instance;
	}
}

优点:

  1. 采用类装载机制,保证初始化实例时只有一个线程
  2. 外部类被装载时不会立即实例化,在用到时才实例化
  3. 类的静态属性只会在第一次加载类的时候初始化,jvm帮助保证线程安全,类进行初始化时别的线程无法进入
  4. 避免了线程不安全,利用静态内部类特点实现延迟加载

枚举
代码实现:

enum Singleton{
	INSTANCE;
}

优点:

  1. 避免多线程同步问题
  2. 防止反序列化重新创建新的对象

总结:后面三种在实际项目中推荐使用,饿汉式可以使用,可能会造成内存资源浪费

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值