我目前正在为简单游戏编写一个库,主要供我自己使用。 现在我遇到了一个问题。我有一个名为“游戏”的类,它看起来像这样:
class Game
{
private List<Entity> entities;
private int counter;
public Game()
{
entities = new List<Entity>();
counter = 0;
}
public AddEntity(Entity entity_)
{
entities.Add(entity_);
// problem! how to inform entity_ that it was added?
counter++;
}
}
实体是一个类,在游戏中起作用的每个对象都必须派生自该类。它的内容并不重要。我正在寻找的是一种让 Game 通知新添加的 entity_ 类有关其所有者(当前 Game 实例)及其 id(这是“计数器”的用途)的方法。现在我一直在考虑使用一个接口(interface),该接口(interface)将具有方法“OnAdd(Game owner_, int id_)”,因为这肯定会起作用,但我想确保没有比这更好的方法。这就是我的问题:
对于我的问题,有没有比接口(interface)更好的解决方案? Entity 实例不知道它被添加到哪个 Game 实例,并且将方法用于类似事件的目的在我看来并不合适。当然,我可能是错的。
请您参考如下方法:
如果您的 Entity 具有 Game 类型的属性,则无需使用事件即可轻松解决此问题:
... code ...
entities.Add(entity_);
entity_.AddToGame(this);
... code ...
然后在 AddToGame 方法中,您将执行您在事件处理程序中执行的任何操作,现在不需要这样做了。
