C#中的一种Singleton的实现(转)

在CSDN上看到了C#中的Singleton的实现,实用性并不是太大,不过里边结合了泛型和多线程同步技术,觉得不错,记一下
//C#代码
//singleton.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Singleton
{
public class SingleTon<T>
{
private static Object objLock = new Object();
protected SingleTon() {}
protected static T _instance;
public static T Instance()
 {
  if(null == _instance)
   {
     lock(objLock)
     {
       if(null == _instance)  //must do this
         _instance = (T)Activator.CreateInstance<T>();
     }
    }
   return _instance;
 }
 public static void Destroy()
  {
    _instance = default(T);
  }
}
 
 public class Person
 {
   String m_strName;
   int    m_nAge;
   public void Eat()
   {
     Console.WriteLine("Eating.. Name: {0}, Age{1}",m_strName,m_nAge);
   }
 }
}
 
//Main.cs
namespace Singleton
{
 class program
{
 static void Main(string[] args)
 {
   SingleTon<Person>.Instance().Eat();
   SingleTon<Person>.Destroy();
 }
}
}
转自:http://12115294.qzone.qq.com/blog/27
posted on 2007-10-03 17:48  老杨的地盘  阅读(400)  评论(1编辑  收藏  举报