Singleton

singleton——单例模式  保证一个类仅有一个实例,并提供一个访问它的全局访问点。

Singleton Code
 1  public class Singleton
2 {
3 private static Singleton instance;
4 public static Singleton Instance
5 {
6 get
7 {
8 return instance;
9 }
10 }
11
12 protected Singleton()
13 {
14 instance = new Singleton();
15 }
16 }

上面这种实现过程又称之为“饿汉模式”,也就是在其他客户对象调用、消费它之前已经初始化了一个singleton的实例。

还有一种就是所谓的“懒汉模式”,即使指Singleton本身一开始并没有初始化一个实例对象,而是在客户第一次消费的时候才产生一个实例对象。代码如下:

懒汉模式
 1     public class Singleton
2 {
3 private static Singleton instance;
4 public static Singleton Instance
5 {
6 get
7 {
8 if (instance == null)
9 {
10 instance = new Singleton();
11 }
12 return instance;
13 }
14 }
15
16 protected Singleton()
17 {
18 }
19 }

在这里“懒汉模式”又分为在多线程下的情况如何初始化instance对象,一般采用如下方式:

多线程下懒汉模式
 1  public class Singleton
2 {
3 private static object obj = new object();
4 private static Singleton instance;
5
6 protected Singleton()
7 {
8 }
9
10 public static Singleton Instance
11 {
12 get
13 {
14 if (instance == null)
15 {
16 lock (obj)
17 {
18 if (instance == null)
19 {
20 instance = new Singleton();
21 }
22 }
23 }
24 return instance;
25 }
26 }
27 }




如果您觉得本文对您有所帮助,请点一下"推荐"按钮,您的"推荐"将是我最大的写作动力!
作者:rpoplar
出处:http://www.cnblogs.com/rpoplar/
本文版权归作者【rpoplar】和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究其法律责任的权利。
原文地址:https://www.cnblogs.com/rpoplar/p/2426170.html