剑指 offer set 28 实现 Singleton 模式

singleton 模式又称单例模式, 它能够保证只有一个实例. 在多线程环境中, 需要小心设计, 防止两个线程同时创建两个实例.

 

解法

1. 能在多线程中工作但效率不高

public sealed class Singleton2 {
	private Singleton2() {

	}

	private static readonly object synObj = new object();
	private static Singleton2 instance = NULL;

	public static Singleton2 instance {
		get{
			lock(synObj) {
				if(instance == NULL)
					instance = new Singleton2();
			}
			return instance;
		}
	}
}

  

上段代码低效在于每次获取 instance 时都会试图加上同步锁, 而加锁本身比较耗时, 应该尽量避免.

改进的方法是在加锁之前另外加一层判断

if(instance == NULL)

  

posted @ 2014-02-24 13:35  SangS  阅读(359)  评论(0编辑  收藏  举报