我想通過我的抽象Charcter類使用Singleton設計模式,所以所有的子類都可以訪問對象實例。這裏是我的單例類:如何通過繼承使用Singleton模式?
class GatewayAccess
{
private static GatewayAccess ph;
// Constructor is 'protected'
protected GatewayAccess()
{
}
public static GatewayAccess Instance()
{
// Uses lazy initialization.
// Note: this is not thread safe.
if (ph == null)
{
ph = new GatewayAccess();
Console.WriteLine("This is the instance");
}
return ph;
}
}
我可以用這個在我的Program.cs創建一個實例沒有問題:
static void Main(string[] args)
{
GameEngine multiplayer = new GameEngine(5);
Character Thor = new Warrior();
Thor.Name = "Raymond";
Thor.Display();
Thor.PerformFight();
Thor.PerformFight();
multiplayer.Attach(Thor);
GatewayAccess s1 = GatewayAccess.Instance();
GatewayAccess s2 = GatewayAccess.Instance();
if (s1 == s2)
{
Console.WriteLine("They are the same");
}
Console.WriteLine(Thor.getGamestate());
Console.ReadLine();
}
所以我想要做的就是讓子類,即,戰士訪問網關的實例,我只是無法弄清楚如何做到這一點,因爲繼承的東西讓我感到困惑。基本上,網關訪問是一個數據庫的訪問點,一次只能有一個連接。單身模式很容易理解,它只是混合了這個和繼承。我希望一旦我達到了這個目標,我就可以以線程安全的方式進行操作。
我還想知道Singleton實例如何被刪除,因爲它是一個數據庫的連接,一次只能被一個字符對象使用,然後一旦字符對象完成了它,它就必須釋放單身對象是正確的?
我試圖在我的Character類中使用方法來完成所有這些,但它不起作用。
我感謝任何幫助。
只是......不。 [單身並不酷](http:// jalf。dk/singleton /) – jalf 2012-04-21 11:24:16