一、单例模式的介绍
单例模式简单说就是掌握系统的至高点,在程序中只实例化一次,这样就是单例模式,在系统比如说你是该系统的登录的第多少人,还有数据库的连接池等地方会使用,单例模式是最简单,最常用的模式之一,面试经常会问答,所以我们在程序考虑什么地方会用到单例模式,单例模式写法有很多种,这里我下面列举2种写法很普遍的写法,然后做个多线程计数的例子大家来理解一下单例模式的用法。
二、单例模式Demo
/// <summary>
/// 利用C#的特性单例模式
/// </summary>
public sealed class SampleSingleton1
{
private int m_Counter = 0;
private SampleSingleton1()
{
Console.WriteLine("初始化SampleSingle1");
}
public static readonly SampleSingleton1 singleton = new SampleSingleton1();
/// <summary>
/// 调用次数计数器
/// </summary>
public void Counter()
{
m_Counter++;
}
}
/// <summary>
/// 线程安全的单例模式
/// </summary>
public class SampleSingleton2
{
private static volatile SampleSingleton2 m_Instance = null;
private int m_Counter = 0;
private SampleSingleton2()
{
Console.WriteLine("初始化SampleSingleton2.");
}
public static SampleSingleton2 Singleton
{
get
{
if (m_Instance == null)
{
lock (typeof(SampleSingleton2))
{
if (m_Instance == null)
{
m_Instance = new SampleSingleton2();
}
}
}
return m_Instance;
}
}
/// <summary>
/// 调用计数器
/// </summary>
public void Couter()
{
m_Counter++;
}
}
/// <summary>
/// 测试2种模式的效率和调用的方式
/// </summary>
DateTime milestone;
int maxCallTimes= 100000000;
// 第一次调用SampleSingleton1的Counter方法
Console.WriteLine("第一次调用SampleSingleton1的Counter方法");
SampleSingleton1.singleton.Counter();
// 计算10000次调用的耗费时间
milestone = DateTime.Now;
for (int i = 0; i < maxCallTimes; i++)
{
SampleSingleton1.singleton.Counter();
}
Console.WriteLine(maxCallTimes.ToString() + "次调用执行时间为:" + ((TimeSpan)(DateTime.Now - milestone)).TotalMilliseconds.ToString());
Console.WriteLine("");
// 第一次调用SampleSingleton2的Counter方法
Console.WriteLine("第一次调用SampleSingleton2的Counter方法");
SampleSingleton2.Singleton.Couter();
// 计算10000次调用的耗费时间
milestone = DateTime.Now;
for (int i = 0; i < maxCallTimes; i++)
{
SampleSingleton2.Singleton.Couter();
}
Console.WriteLine(maxCallTimes.ToString() + "次调用执行时间为:" + ((TimeSpan)(DateTime.Now - milestone)).TotalMilliseconds.ToString());
string str = Console.ReadLine();
}
三、GitHub的地址
https://github.com/wangtongzhou520/Designpattern