使用静态类来简化单件
呵呵,看图看代码说话:) 可能我也是错的。
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace Singleton
{
static class Singleton<T> where T : class, new()
{
static Singleton()
{ }
public static readonly T Instance = Activator.CreateInstance<T>();
}
}
测试类,我想创建谁的单件就创建谁的单件。(说的夸张了点)using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace Singleton
{
static class Singleton<T> where T : class, new()
{
static Singleton()
{ }
public static readonly T Instance = Activator.CreateInstance<T>();
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Singleton
{
class Test
{
private int nCount;
public Test()
{
nCount = 0;
}
public void RecordCount()
{
nCount++;
}
public void Display()
{
Console.WriteLine(nCount);
}
}
}
测试代码:using System.Collections.Generic;
using System.Text;
namespace Singleton
{
class Test
{
private int nCount;
public Test()
{
nCount = 0;
}
public void RecordCount()
{
nCount++;
}
public void Display()
{
Console.WriteLine(nCount);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Singleton
{
class Program
{
static void Main(string[] args)
{
Test test1 = Singleton<Test>.Instance;
test1.RecordCount();
test1.Display();
Test test2 = Singleton<Test>.Instance;
test2.RecordCount();
test2.Display();
Console.WriteLine(test1 == test2);
Console.Read();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace Singleton
{
class Program
{
static void Main(string[] args)
{
Test test1 = Singleton<Test>.Instance;
test1.RecordCount();
test1.Display();
Test test2 = Singleton<Test>.Instance;
test2.RecordCount();
test2.Display();
Console.WriteLine(test1 == test2);
Console.Read();
}
}
}