剑指offer--(2.2)面试题2:实现Singleton模式

 剑指offer--(2.2)面试题2:实现Singleton模式


题目:设计一个类,我们只能生成该类的一个实例

这个题目容易考,但是我写的都是课本中会提到的,看到一个博主,非常推荐去学习他的文章:

https://blog.csdn.net/derrantcm/article/details/45330779

他的博文知识更多。

/*
1.只适用于单线程环境
*/
public sealed class Singlethon1
{
	private Singlethon1
	{
	}

	private static Singleton1 instance = null;
	public static Singlethon1 Instance
	{
		get
		{
			if (instance == null)
				instance = new Singlethon1();

			return instance;
		}
	}
}


/*
2.虽然在多线程环境能工作但效率不高
*/

public sealed class Singleton2
{
	private Singleton2()
	{
	}

	private static readonly object syncObj = new object();

	private static Singleton2 instance = null;
	public static Singleton2 Instance
	{
		get
		{
			lock(syncObj)
			{
				if(instance == null)
					instance = new Singleton2();
			}

			return instance;
		}
	}
}



/*
 3. 可行的解法,加同步锁前后两次判断实例是否已存在
*/
public sealede class Singlenton3
{
    private Singleton3()
	{
	}

	private static object syncObj = new object();

	private static Singleton3 instance = null;
	public static Singleton3 Instance 
	{
		get
		{
			if(instance == null)
			{
				lock(syncObj)
				{
					if(instance ==null)
					{
						instance = new Singleton3();
					}
                 }
			}
			return instance;
		}
	}
}

/*
推荐一:C#中利用静态构造函数
*/

public sealed class Singleton4
{
	private Singleton4
	{
	}

	private static Singleton4 instance = new Singleton4();
	public static Singleton4 Instance
	{
		get
		{
			return instance;
		}
	}
}


/*
5.推荐二:实现按需创建实例
*/

public sealed class Singleton5
{
	Singleton5()
	{
	}

	public static Singleton5 Instance
	{
		get
		{
		     return Nested.instance;
		}
	}

	class Nested
	{
		static Nested()
		{
		}

		internal static readonly Singleton5 instance = new Singleton5();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41103495/article/details/105476913