“隐瞒”有什么不好吗?静态类中的单例结构以便更容易编写?

发布于 2025-01-17 06:54:01 字数 1200 浏览 3 评论 0原文

拿这个例子(不是我真正使用的):

using System;
using System.Collections.Generic;

/// <summary>
/// secrete singleton structure
/// </summary>
public sealed class NameChecker
{
    private static NameChecker _instance;
    private static readonly object padlock = new object();

    public static NameChecker Instance
    {
        get
        {
            lock( padlock )
            {
                if( _instance == null )
                {
                    _instance = new NameChecker();
                }
                return _instance;
            }
        }
    }

    private List<string> names = new List<string>();

    public static bool IsUnique( string key )
    {
        return NameChecker.Instance.names.Contains( key );
    }

    public static void AddName( string key )
    {
        NameChecker.Instance.names.Add( key );
    }

    public static void RemoveName( string key )
    {
        NameChecker.Instance.names.Remove( key );
    }

}

使用这个我可以写 NameChecker.IsUnique("Sally") 而不是写 NameChecker.Instance.IsUnique("Sally)。我在 NameChecker 中添加了一个注释,所以至少在 Visual Studio 上你会知道它有一个单例实现。

对我来说,这似乎是构建单例类的最佳方法。
这会遇到什么问题吗?

Take this example (not something I really use):

using System;
using System.Collections.Generic;

/// <summary>
/// secrete singleton structure
/// </summary>
public sealed class NameChecker
{
    private static NameChecker _instance;
    private static readonly object padlock = new object();

    public static NameChecker Instance
    {
        get
        {
            lock( padlock )
            {
                if( _instance == null )
                {
                    _instance = new NameChecker();
                }
                return _instance;
            }
        }
    }

    private List<string> names = new List<string>();

    public static bool IsUnique( string key )
    {
        return NameChecker.Instance.names.Contains( key );
    }

    public static void AddName( string key )
    {
        NameChecker.Instance.names.Add( key );
    }

    public static void RemoveName( string key )
    {
        NameChecker.Instance.names.Remove( key );
    }

}

using this I can write NameChecker.IsUnique("Sally") instead of writing NameChecker.Instance.IsUnique("Sally). I include a note with NameChecker so at least on Visual Studio you'll know it's got a singleton implementation.

To me, it seems like the best way to build a singleton class.
Is there any kind of problem this would run into?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开柳相依 2025-01-24 06:54:01

是的,一方面它使单元测试变得困难。

Yes, for one thing it makes unit testing hard.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文