乐乐

乐乐的博客园
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c#单态模式与泛型结合的使用方法

Posted on 2007-05-21 10:50  带你去月球  阅读(718)  评论(2)    收藏  举报
 public class SingletonProvider<T> where T : new()
{
 SingletonProvider() 
{ }

 
public static T Instance
 
{
  
get return SingletonCreator.instance; }
 }


 
class SingletonCreator
 
{
  
static SingletonCreator() { }
  
internal static readonly T instance = new T();
 }

}

 Test:
public class TestClass
{
 
private string _createdTimestamp;

 
public TestClass ()
 
{
  _createdTimestamp 
= DateTime.Now.ToString();
 }


 
public void Write()
 
{
  Debug.WriteLine(_createdTimestamp);
 }

}
==> : SingletonProvider<TestClass>.Instance.Write();


 //另一个实现singleton的方法,不用约束的。
 public static class Singleton<T>
    {
        private static T instance;
        public static T NewInstance()
        {
            if (instance == null)
            {
                instance = (T) Activator.CreateInstance(typeof(T), true);
            }
            return instance;
        }
    }

无觅相关文章插件,快速提升流量