我们可以使用公共构造函数的单例类吗? [英] Can we have singleton class with public constructor?
本文介绍了我们可以使用公共构造函数的单例类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以用public构造函数实现单一吗?如果是这样做有什么好处?
解决方案
嗯,你可以...但是它不是一个单身人士类。
单例类的想法是它只允许类的单个实例存在 - 所以通过允许类外的世界调用构造函数来使公共构造函数公开。创建任意数量的实例:除非构造函数查找并抛出运行时错误。哪个是糟糕的设计,因为它会产生应该作为编译时捕获的运行时问题!
嗯,是的,你可以这样做:< span class =code-comment> // 非静态Ctor:静态内部实例
public class OpenDoorSingleton1
{
private static OpenDoorSingleton1 _instance;
private string _aString;
public string AString
{
set { if (_instance!= null )_instance ._aString = value ; }
get
{
if (_ instance != null )
{
return _instance._aString;
}
其他
{
返回 串跨度> .Empty;
}
}
}
// 隐藏无参数ctor
受保护 OpenDoorSingleton1()
{
}
public static OpenDoorSingleton1 StaticInstantiate()
{
if (_instance == null )_ instance = new OpenDoorSingleton1();
return _instance;
}
public OpenDoorSingleton1( string astring)
{
_instance = StaticInstantiate();
_instance.AString = astring;
}
}这有一个允许你使用参数的公共构造函数,但是,看看你必须经历的所有麻烦,以避免递归和堆栈溢出! />
我永远不会使用这样的代码:你隐藏的目的是让它成为一个只有一个实例的类!
<浏览:Jon Skeet:[ ^ ],以及Singleton的DoFactory样本(免费):[ ^ ]。
Can implement single with public constructor? and if yes what is the advantage of doing this?
解决方案
Well, you can...but then it isn't a singleton class.
The idea of a singleton class is that it only allows a single instance of the class to exist - so making the constructor public circumvents this by allowing the world outside the class to call the constructor and create as many instances as it wanted: unless the constructor looked for this and threw a run-time error. Which is poor design, because it creates runtime problems that should have been caught as compile time!
Well, yes, you can do something like this:// non-static Ctor: static internal instance public class OpenDoorSingleton1 { private static OpenDoorSingleton1 _instance; private string _aString; public string AString { set { if (_instance != null) _instance._aString = value; } get { if (_instance != null) { return _instance._aString; } else { return string.Empty; } } } // hidden parameterless ctor protected OpenDoorSingleton1() { } public static OpenDoorSingleton1 StaticInstantiate() { if (_instance == null) _instance = new OpenDoorSingleton1(); return _instance; } public OpenDoorSingleton1(string astring) { _instance = StaticInstantiate(); _instance.AString = astring; } }This has a public constructor that lets you use parameters, but, look at all the trouble you had to go through to avoid recursion and stack overflow here !
I would never use code like this: you are hiding the intention to make this a one-and-only-one instance Class !
See: Jon Skeet: [^], and, the DoFactory sample for Singleton (free): [^].
这篇关于我们可以使用公共构造函数的单例类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文