1

我正在尝试通过我的抽象 Charcter 类使用 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();
    }

所以我想做的是允许子类,即战士访问网关的实例,我只是不知道如何做到这一点,因为继承的东西让我感到困惑。基本上,网关访问是对一次只能有一个连接的数据库的访问点。单例模式很容易理解,它只是它和继承的混合。我希望一旦我实现了这一点,我就可以以线程安全的方式做到这一点。

我还想知道如何删除单例实例,因为它是与数据库的连接,一次只能由一个角色对象使用,然后一旦角色对象完成,它必须释放单例对象对?

我试图在我的 Character 类中使用方法来完成这一切,但它不起作用。

我很感激这方面的任何帮助。

4

3 回答 3

4

我在这里感觉到了几种设计气味。

  • 数据库连接不应该是单例 - 正如您自己提到的那样,连接来来去去,而单例的主要观点是它会在应用程序的生命周期内保持不变
  • 单例和线程安全不是很好的匹配
  • 游戏角色不应该与网关一起工作(来吧,战士与数据库有什么关系?;-)

您应该更好地分离关注点,并让 DB / 持久性由调用游戏角色的不同类处理,而不是反之亦然。

您提供的信息很少,很难给出更具体的建议。

于 2012-04-21T11:39:06.157 回答
1

您可以使用简单的static class,而不是单音,您不能扩展它,也不能创建它的实例。另外,您可以通过简单地在其上调用一个函数来以您想要的方式使用static它,并且它可以在内部跟踪private static connection成员的状态。

编辑

只是一个伪代码示例:

public static class Connector
{
    static SqlConnection con = new SqlConnection(...); //return type object, 
                                                       //just for example, choose more 
                                                       //appropriate type for you.

    public static object GetData(string query)
    {
       con.Open();

       //run query and retrieve results

       con.Close();
    }
}

希望这可以帮助。

于 2012-04-21T11:33:16.987 回答
1

单例绝对不是好的模式,当它应该只被一个对象使用时。为什么不将它创建为该 Character 类的非静态字段并在 IDispose.Dispose() 中销毁它?如果您仍然想要单例,请保护“ph”,然后您可以将其作为 GatewayAccess.ph 访问

于 2012-04-21T11:37:52.733 回答