.net 单例设计模式

前几天,在研究QQ项目,用的是三层模式做的,大致的做好之后,发现写得有点乱,主要是窗体之间的静态变量太多。后来看到别人博客谢了一个例子,有点感触:

 

 

Singleton模式的实现
Singleton模式的实现基于两个要点:
1)不直接用类的构造函数,而另外提供一个Public的静态方法来构造类的实例。通常这个方法取名为Instance。Public保证了它的全局可见性,静态方法保证了不会创建出多余的实例。
2)将类的构造函数设为Private,即将构造函数"隐藏"起来,任何企图使用构造函数创建实例的方法都将报错。这样就阻止了开发人员绕过上面的Instance方法直接创建类的实例。
通过以上两点就可以完全控制类的创建:无论有多少地方需要用到这个类,它们访问的都是类的唯一生成的那个实例。以下C#代码展现了两种实现Singleton模式的方式,开发人员可以根据喜好任选其一。
实现方式一:Singleton.cs
using System;
class SingletonDemo
{ private static SingletonDemo theSingleton = null;
 private SingletonDemo() {}
 public static SingletonDemo Instance()
 { if (null == theSingleton)
  {
   theSingleton = new SingletonDemo();
  }
  return theSingleton;
 }
 static void Main(string[] args)
 { SingletonDemo s1 = SingletonDemo.Instance();
  SingletonDemo s2 = SingletonDemo.Instance();
  if (s1.Equals(s2))
  { Console.WriteLine("see, only one instance!");
  }
 }
}
  与之等价的另外一种实现方式是:Singleton.cs:
using System;

class SingletonDemo
{ private static SingletonDemo theSingleton = new SingletonDemo();
 private SingletonDemo() {}
 public static SingletonDemo Instance()
 { return theSingleton;
 }
 static void Main(string[] args)
 { SingletonDemo s1 = SingletonDemo.Instance();
  SingletonDemo s2 = SingletonDemo.Instance();
  if (s1.Equals(s2))
  { Console.WriteLine("see, only one instance!");
  }
 }
}
  编译执行:
Csc Singleton.cs
得到运行结果:
see, only one instance!

 

 

 

 

 

 

深有感触。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值