Singleton Pattern

什么是单例

整个系统中某个类只有一个实例。

单例有什么用

单例相当于是系统的一个全局变量。

应用场景:系统的配置信息存放于文件中,通过一个类的单例对象读取配置文件,有利于整个系统对配置信息的统一调度管理。

(还有哪些应用场景?)

java 单例实现

饿汉式,在类加载时构建单例对象

public class Singleton {
	private static Singleton instance = new Singleton();   // 有人在此处加了 final 修饰符,有必要吗?为什么
	private Singleton(){}
	public static Singleton getInstance(){
		return instance;
	}
}

懒汉式,在单例对象第一次被使用时构建,


单线程时

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

多线程,加锁,但每次都验证锁造成效率问题

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

double-check,提升效率

public class Singleton {
	private static Singleton instance = null;
	private Singleton(){}
	public static Singleton getInstance(){
		
		//double-check 
		if(instance == null){ //提升效率
			synchronized (Singleton.class) { //保证单例
				if(instance == null){
					instance = new Singleton();
				}
			}
		}
		return instance;
	}
}

但double-check在jdk 1.5 之前某些情况下会发生非预期问题  The "Double-Checked Locking is Broken" Declaration

1.5 及以后版本加上 volatile 修饰可避免非预期问题

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

c/c++ 单例实现方式


参考文档

深入浅出单实例Singleton设计模式   by 陈浩

单例模式-维基百科

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值