Cracking the coding interview--Q18.3

题目

原文:

Implement a singleton design pattern as a template such that, for any given class Foo, you can call Singleton::instance() and get a pointer to an instance of a singleton of type Foo. Assume the existence of a class Lock which has acquire() and release() methods. How could you make your implementation thread safe and exception safe?

译文:

实现一个单例模式模板,当给一个类Foo时,你可以调用Singleton::instance()来得到一个指向Foo单例的指针,假设我们现在已经有了Lock类,其中有acquire() 和release()两个方法,你要如何使你的实现线程安全且异常安全?

解答

class Singleton<T>{
	private static Lock lock;
	private T object;
	public static T instance(){
		if(object==null){
			lock.AcquireLock();
			if(object==null){
				object=new T();
			}
			lock.ReleaseLock();
		}
		return object;
	}
	public static void main(String[] args){
		Foo singleton_foo=Singleton<Foo>.instance();
	}
}

class Foo{

}

class Lock{

	Lock(){}

	public void AcquireLock(){

	}

	public void ReleaseLock(){

	}

}


附:单例模式的七种写法:

//1.懒汉式,线程不安全,多线程不能工作
class Singleton{
	private static Singleton instance;
	private Singleton(){}
	public static Singleton getInstance(){
		if(instance==null){
			instance=new Singleton();
		}
		return instance;
	}
}

//2.懒汉式,线程安全,但效率低,99%情况下不需要同步
class Singleton{
	private static Singleton instance;
	private Singleton(){}
	public static synchronized Singleton getInstance(){
		if(instance==null){
			instance=new Singleton();
		}
		return instance;
	}
}

//3.饿汉式,避免了多线程的同步问题,instance在类装载时就实例化,但是也不能确定有其他的方式(或者其他的静态方法)导致类装载
class Singleton{
	private static Singleton instance=new Singleton();
	private Singleton(){}
	public static Singleton getInstance(){
		return instance;
	}
}

//4.饿汉式,变种,和第三种差不多,都是在类初始化即实例化instance
class Singleton{
	private Singleton instance=null;
	static{
		instance=new Singleton();
	}
	private Singleton(){}
	public static Singleton getInstance(){
		return this.instance;
	}
}

//5.静态内部类,利用了classloder的机制来保证初始化instance时只有一个线程Singleton类被装载了,instance不一定被初始化。
//因为SingletonHolder类没有被主动使用,只有显示通过调用getInstance方法时,才会显示装载SingletonHolder类,从而实例化instance
class Singleton{
	private static class SingletonHolder{
		private static final Singleton INSTANCE=new Singleton();
	}
	private Singleton(){}
	public static final Singleton getInstance(){
		return SingletonHolder.INSTANCE;
	}
}

//6.枚举,不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,但比较少用
public enum Singleton{
	INSTANCE;
	public void whateverMethod(){

	}
}

//7.双重校验锁,这个是第二种方式的升级版,俗称双重检查锁定
class Singleton{
	private volatile static Singleton singleton;
	private Singleton(){}
	public static Singleton getSingleton(){
		if(singleton==null){
			synchronized(Singleton.class){
				if(singleton==null){
					singleton=new Singleton();
				}
			}
		}
	}
	return singleton;
}


---EOF---

你可能感兴趣的:(Cracking the coding interview--Q18.3)