當我通過下面的代碼,我無法找到它在示例中使用私有構造函數的原因?私人構造函數在單例設計模式中需要什麼?
public sealed class Singleton
{
private static Singleton instance = null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
...
//Why shouldnt I use something like below.
public class Singleton
{
private static Singleton instance = null;
static Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
,而不是公共類,如果我創建了一個靜態類,我可以使用類,而不是直接創建實例。 當靜態關鍵字一直存在於同一個工作中時,需要在這裏創建一個私有構造函數嗎?
遵循此模式的其他優點?
https://www.michaelsafyan.com/tech/design/patterns/singleton – Idos
這不是一個單身人士,沒有實例方法。私人構造函數只是防止客戶端代碼創建一個實例(這不需要任何東西)。類的靜態修飾符僅在C#2中引入 - 也許代碼早於此,否則作者不知道它。 –
我已經更新了代碼。 –