I am trying to use the Singleton design pattern via my abstract Charcter class so all sub classes can acces the object instance. Here is my singleton class:
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;
}
}
I can use this in my program.cs to create an instance no problem:
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();
}
So what I want to do is allow the subclasses ie, warrior to access the instance of the Gateway, I just cannot figure out how to do this as the inheritance stuff is confusing me. Basically the gateway access is an access point to a database that can only have one connection at once. The singleton pattern was easy enough to understand, its just the mix of that and the inheritance. I was hoping once I achieved this, I could then do it in a thread safe manner.
I was also wondering how the Singleton instance could be dropped, as it is a connection to a database and can only be used by one character object at a time, then once the character object is done with it, it must free the singleton object up right?
I tried to use methods in my Character class to do all this but it isn't working.
I appreciate any help with this.