如何通过继承使用Singleton模式? [英] How to use the Singleton pattern via inheritance?
问题描述
我试图通过我的抽象Charcter类使用Singleton设计模式,以便所有子类都可以访问对象实例.这是我的单例课程:
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;
}
}
我可以在program.cs中使用它来创建实例,没问题:
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();
}
所以我想做的是允许子类(即warrior)访问Gateway的实例,我只是不知道如何做到这一点,因为继承的东西使我感到困惑.基本上,网关访问是对数据库的访问点,该数据库只能一次只有一个连接.单例模式很容易理解,只是它与继承的结合.我希望一旦实现这一目标,便可以以线程安全的方式做到这一点.
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.
我还想知道如何删除Singleton实例,因为它是与数据库的连接,一次只能由一个字符对象使用,然后一旦完成字符对象,它就必须释放单例对象对不对?
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?
我试图使用我的Character类中的方法来完成所有这些操作,但是它不起作用.
I tried to use methods in my Character class to do all this but it isn't working.
我对此表示感谢.
推荐答案
我在这里感觉到一些设计异味.
I sense several design smells here.
- 数据库连接不应该是Singleton-正如您自己提到的那样,连接来来去去,而Singleton的要点是它在应用程序的生命周期中一直存在
- 单线程和线程安全性不是很好的匹配
- 游戏角色不必使用网关(来吧,战士对数据库有什么用?;-)
您最好将关注点分开,并让DB/持久性由另一个类来处理,这些类调用游戏角色,而不是相反.
You should better separate concerns and have DB / persistence handled by a different class which calls the game characters rather than vice versa.
仅凭您提供的少量信息很难给出更具体的建议.
It is difficult to give more specific advice with the little information you provided.
这篇关于如何通过继承使用Singleton模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!