北溟鱼逍遥游

王猛扪虱谈天下 孟德煮酒论英雄

导航

Singleton

using System;

public sealed class Singleton1
{
 static Singleton1 instance;
 Singleton1(){}
 public static Singleton1 Instance
 {
  get{
  if (instance == null)
  instance = new Singleton1();
  return instance;
 }
 }
}

public sealed class Singleton2
{
 static Singleton2 instance;
 static readonly object padlock = new object();
 
 public static Singleton2 Instance
 {
  get
  {
   lock (padlock)
   {
    if (instance == null)
    instance = new Singleton2();
   }
   return instance;
  }
 }
}

public sealed class Singleton3
{
 static Singleton3 instance;
 static readonly object padlock = new object();
 public static Singleton3 Instance
 {
  get{
  if (instance == null)
  lock(padlock){
  if (instance == null){
  instance = new Singleton3();
 }
}
       return instance;
}
 }
}

public sealed class Singleton4
{
 static readonly Singleton4 instance = new Singleton4();
 static Singleton4(){}
 Singleton4(){}
 
 public static Singleton4 Instance
 {
  get{
  return instance;
 }
}
}

public sealed class Singleton5
{
 Singleton5(){}
 
 public static Singleton5 Instance
 {
  get{
  return Nested.instance;
 }
}
 
 class Nested{
 static Nested(){}
 internal static readonly Singleton5 instance = new Singleton5();
 }
}

posted on 2005-03-15 10:12  北溟鱼逍遥游  阅读(708)  评论(0编辑  收藏  举报