使用静态类来简化单件

呵呵,看图看代码说话:) 可能我也是错的。

using System;
using System.Collections.Generic;
using System.Text;

using System.Reflection;

namespace Singleton
{
    
static class Singleton<T> where T : classnew()
    {
        
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;
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();
        }
    }
}

posted on 2006-07-13 18:12  萝卜青菜  阅读(300)  评论(1编辑  收藏  举报

导航