设计模式1:单例模式(考虑多线程的情况)

单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点,可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制,“阻止”所有想要生成对象的访问。使用工厂方法来限制实例化过程。这个方法应该是静态方法(类方法),因为让类的实例去生成另一个唯一实例毫无意义。

 

饿汉式代码如下:

 

package zhaodp.demo;

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


设计模式的教科书上的示例一般与上述代码类似。如果在多线程环境下,instance()方法可能会出现问题,如何才能做到线程安全呢,可以将代码变成:

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

将instance方法加上synchronized进行限定,确实可以解决线程安全问题,但会造成多线程调用该方法时串行执行,效率低下,如何改进呢?以下代码既可以保证线程安全又可以提高多线程并发的效率。

package zhaodp.demo;

public class Singleton {
	private static Singleton uniqueInstance = null;

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


 

或者这么写:

package zhaodp.demo;

public class Singleton {
	private static Singleton uniqueInstance = null;

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


 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值