Singleton

博客展示了C#中五种单例模式的实现代码。包括简单懒汉式、加锁懒汉式、双重检查锁定、饿汉式和静态内部类实现方式,每种方式都有对应的代码示例,可用于在C#编程中实现单例模式。

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();
 }
}

转载于:https://www.cnblogs.com/archmaster/archive/2005/03/15/118899.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值