using System;
using System.Linq;
using System.Text;
namespace Ahoo.Demo.DesignPatterns.Patterns.Singleton
{
/* ####### 单例模式 #######
* 保证一个类只有一个实例,
* 并提供一个全局访问点
*/
/// <summary>
/// 懒汉式单例类
/// </summary>
public class Singleton
{
/// <summary>
/// 静态唯一实例
/// 第一次调用时初始化
/// </summary>
private static Singleton instance;
/// <summary>
/// 同步锁
/// </summary>
private static readonly object syncRoot = new object();
/// <summary>
/// 私有化构造函数
/// </summary>
private Singleton()
{
}
/// <summary>
/// 双重锁,降低锁机制造成的性能影响
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
/// <summary>
/// 恶汉式单例类
/// </summary>
public class Singleton2
{
/// <summary>
/// 程序启动时即初始化实例
/// </summary>
private static readonly Singleton2 instance = new Singleton2();
/// <summary>
/// 私有化构造函数
/// </summary>
private Singleton2()
{
}
public static Singleton2 GetInstance()
{
return instance;
}
}
public class Client
{
public static void Excute()
{
Singleton singleton = Singleton.GetInstance();
Singleton2 singleton2 = Singleton2.GetInstance();
}
}
}