单件模式
代码
using System;
using System.Collections.Generic;
/// <summary>
/// 单件模式(线程安全的单件(双重锁定方法2:线程安全而且性能优越))
/// </summary>
public class Singleton
{
/// <summary>
/// 定义自身静态变量实例默认为null
/// </summary>
private static Singleton instance=null;
private static readonly object olock=new Object();
///私有构造函数
/// 之所以不为public类型,因为是为了避免发生new Singleton()产生实例
private Singleton()
{}
public static Singleton getInstance()
{
if(instance==null)
{
lock(olock)
{
if(instance==null)
{
instance=new Singleton();
}
return instance;
}
}
}
}
using System.Collections.Generic;
/// <summary>
/// 单件模式(线程安全的单件(双重锁定方法2:线程安全而且性能优越))
/// </summary>
public class Singleton
{
/// <summary>
/// 定义自身静态变量实例默认为null
/// </summary>
private static Singleton instance=null;
private static readonly object olock=new Object();
///私有构造函数
/// 之所以不为public类型,因为是为了避免发生new Singleton()产生实例
private Singleton()
{}
public static Singleton getInstance()
{
if(instance==null)
{
lock(olock)
{
if(instance==null)
{
instance=new Singleton();
}
return instance;
}
}
}
}
1 public static Singleton GetInstance()
2 {
3 if (singleton == null)
4 {
5 lock (syncObject)
6 {
7
8 if (singleton == null)
9 {
10 singleton = new Singleton();
11 }
12 }
13 }
14 return singleton;
15 }
2 {
3 if (singleton == null)
4 {
5 lock (syncObject)
6 {
7
8 if (singleton == null)
9 {
10 singleton = new Singleton();
11 }
12 }
13 }
14 return singleton;
15 }
1 namespace Singleton
2 {
3 public sealed class Singleton
4 {
5 private static readonly Singleton singleton = new Singleton();
6
7 private Singleton()
8 {
9 }
10
11 public static Singleton GetInstance()
12 {
13 return singleton;
14 }
15 }
16 }
2 {
3 public sealed class Singleton
4 {
5 private static readonly Singleton singleton = new Singleton();
6
7 private Singleton()
8 {
9 }
10
11 public static Singleton GetInstance()
12 {
13 return singleton;
14 }
15 }
16 }