第六章 基本框架(Framework)
二 单例模式(Singleton)
单例模式,就是指一个类只有一个对象实例。
1 单例(Singleton.cs)
单例大家已经非常熟悉了,这里和一般单例没什么区别。只是多继承了一个IDisposable
接口。直接上代码了。
using System;
namespace DR.Book.SRPG_Dev.Framework
{
public abstract class Singleton<T> : IDisposable where T : Singleton<T>, new()
{
/// <summary>
/// 用于线程锁定
/// </summary>
private static object s_lock = new object();
private static T s_Instance;
/// <summary>
/// 单例
/// </summary>
public static T instance
{
get
{
if (s_Instance == null)
{
lock (s_lock)
{
if (s_Instance == null)
{
s_Instance = new T();
}
}
}
return s_Instance;
}