wiki的說明 singleton pattern 的實現常見有
lazy instantization 跟 eager instantization
依造設計用意
lazy 在第一次使用時才產生實例
eager 是物件載入時產生
不了解何時是所謂的"物件載入"
實際用以下2個class測試, 環境是 vs 2010 express
public class Singleton_lazy
{
private static Singleton_lazy instance;
public static string str = "lazy public attribute";
private Singleton_lazy()
{
Console.WriteLine("Singleton lazy initialized");
}
public static Singleton_lazy getInstance()
{
if (instance == null)
instance = new Singleton_lazy();
return instance;
}
public static string String()
{
return "lazy public method";
}
}
public class Singleton_Eager
{
private static readonly Singleton_Eager instance = new Singleton_Eager();
public static string str = "eager public attribute";
private Singleton_Eager()
{
Console.WriteLine("Singleton Eager initialized");
}
public static Singleton_Eager getInstance()
{
return instance;
}
public static string String()
{
return "eager public method";
}
}
測試3種情況