rex的博客

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

利用c#2.0的范型加上一点反射,构造了一个自认为不错的Singleton实现.

 

public class Singleton<T>
    
{
        
protected Singleton()
        
{
             
//Assert class T don't have public constructor
             
//Assert class T have a private/protected parameterless constructor
        }


        
protected static T _instance;
        
public static T Instance()
        
{
            
//Assert class T don't have public constructor
            
//Assert class T have a private/protected parameterless constructor
            
//Assert class T is not abstract and is not an interface

            
if (_instance == null)
            
{
                    _instance 
= (T)Activator.CreateInstance(typeof(T),true);//use reflection to create instance of T
            }

            
return _instance;
        }


        
public void Destroy()
        
{
            _instance 
= default(T);
        }

    }
使用也很方便;例如
class Foo
{
    
private Foo()//must declare,or assert will fail in the singleton class
    {
    }

    
    
public void Bar()
    
{
        
    }

}




void Test()
{
    Singleton
<Foo>.Instance().Bar();
}
甚至可以这样定义一个类:
public class Foo : Singleton<Foo>
{
    
protected Foo()//must declare
    {
    }

    
    
public void Bar()
    
{
        
    }

}





void Test()
{
    Foo.Instance().Bar();
}
posted on 2006-01-12 17:46  rex  阅读(4681)  评论(28编辑  收藏  举报