#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
#endregion
namespace GenericsSingleton
{
/// <summary>
/// 單例范型
/// </summary>
/// <typeparam name="T"></typeparam>
public class Singleton<T>
{
private static T _instance;
public Singleton()
{
}
public static T Instance
{
get
{
if (_instance == null)
{
//獲得實例,使用這個方法的前提是T要有公有的、無參數的構造函數
_instance = (T)System.Activator.CreateInstance(typeof(T));
}
return _instance;
}
}
}
/// <summary>
/// 要實現單例的類
/// </summary>
public class Foo
{
private int count = 0;
public int Count
{
get
{
count++;
return count;
}
}
}
/// <summary>
/// 主函數
/// </summary>
class Program
{
static void Main(string[] args)
{
//連續調用三次如果值是遞增的話說明三次調用都是同一個實例
Console.WriteLine(Singleton<Foo>.Instance.Count);
Console.WriteLine(Singleton<Foo>.Instance.Count);
Console.WriteLine(Singleton<Foo>.Instance.Count);
Console.ReadLine();
}
}
}