代码改变世界

设计模式:单件模式

  敏捷的水  阅读(508)  评论(0编辑  收藏  举报

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

1. 单线程时方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.线程安全的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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. 双重锁定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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. 静态初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public sealed class Singlton
{
    static readonly Singlton instance = new Singlton();
 
    static Singlton()
    { }
 
    public static Singlton Instance
    {
        get
        {
            return instance;
        }
    }
}

5. 延迟静态初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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() { }
    }
}
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示