Head First---单件模式

单间模式是工作中遇到的比较多的一种模式,也叫单例模式。

单间模式确保一个类只有一个实例,并提供一个全局访问点。


创建单例模式主要有四种方法:

(1)第一种要介绍的方法,也是我在工作中用的最多的方法,看过Head First后就了解此方法的最大缺点。

public class Singleton {

	private static Singleton uniqueInstance;

	public static Singleton getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new Singleton();
		}
		return uniqueInstance;
	}

}

此方法在单线程中使用时没有问题,也存在效率问题,但是现在的应用基本都是多线程,当在多线程中使用时就可能导致创建两个实例。


(2)第二种方法是在getInstance方法前面加上同步synchronized关键字。

public class Singleton {

	private static Singleton uniqueInstance;

	//加上synchronized关键字
	public synchronized static Singleton getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new Singleton();
		}
		return uniqueInstance;
	}

}

此方法的最大弊端很显然是同步关键字引起的性能问题,同步一个方法可能造成程序执行效率下降100倍。如果应用可以接受同步方法带来额外负担,就可以使用此方法。


(3)第三种方法使用“急切“创建实例,而不用延迟实例化的做法,即在定义静态变量的时候来创建单间。

public class Singleton {

	private static Singleton uniqueInstance = new Singleton();

	public synchronized static Singleton getInstance() {
		return uniqueInstance;
	}

}

如果使用单例是,在创建或者运行时的负担不太繁重时,可以使用。另外在创建时做一些初始化工作,而且也要传入一些参数时,这种方法就有可能不能满足需求。


(4)第四种方法是使用”双重检查加锁“,在getInstance中减少同步的使用。

public class Singleton {

	// 使用了volatile关键字
	private static volatile Singleton uniqueInstance;

	public synchronized static Singleton getInstance() {
		if (uniqueInstance == null) {

			synchronized (Singleton.class) {
				if (uniqueInstance == null) {
					uniqueInstance = new Singleton();
				}
			}
		}
		return uniqueInstance;
	}

}

从代码中可以可以看到,只有第一次需要同步,这个方法大大的减少了getInstance的时间耗费。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值