“隐瞒”有什么不好吗?静态类中的单例结构以便更容易编写?
拿这个例子(不是我真正使用的):
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,一方面它使单元测试变得困难。
Yes, for one thing it makes unit testing hard.