设计模式:单件模式

本文详细介绍了Singleton模式的五种实现方式,包括单线程时的方法、线程安全的实现、双重锁定、静态初始化以及延迟静态初始化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点。

1. 单线程时方法

public sealed class Singlton 
{ 
    static Singlton instance = null; 
    Singlton() 
    { } 
  
    public static Singlton Instance 
    { 
        get
        { 
            if (instance == null) 
            { 
                return new Singlton(); 
            } 
            return instance; 
        }     
    }     
} 
这句if (instance == null)不是线程安全的,可能产生多个实例。

2.线程安全的
public sealed class Singlton 
{ 
    static Singlton instance = null; 
  
    static readonly object o = new object(); 
  
    Singlton() 
    { } 
  
    public static Singlton Instance 
    { 
        get
        { 
            lock (o) 
            { 
                if (instance == null) 
                { 
                    return new Singlton(); 
                } 
                return instance; 
            } 
        }     
    }     
} 
对象实例由最先进入的那个线程创建,后来的线程在进入时(instence == null)为假,不会再去创建对象实例了。但是这种实现方式增加了额外的开销,损失了性能。

3. 双重锁定
 public sealed class Singlton 
{ 
    static Singlton instance = null; 
  
    static readonly object o = new object(); 
  
    Singlton() 
    { } 
  
    public static Singlton Instance 
    { 
        get
        { 
            if (instance == null) 
            { 
                lock (o) 
                { 
                    if (instance == null) 
                    { 
                        return new Singlton(); 
                    } 
                } 
            } 
            return instance; 
        } 
    } 
} 
避免了每个 Instance 属性方法的调用中都出现独占锁定。

4. 静态初始化
public sealed class Singlton 
{ 
    static readonly Singlton instance = new Singlton(); 
  
    static Singlton() 
    { } 
  
    public static Singlton Instance 
    { 
        get
        { 
            return instance; 
        } 
    } 
} 
5. 延迟静态初始化

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

 

转载于:https://www.cnblogs.com/profession/p/5073069.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值