我正在尝试为一个游戏设计几个类,但是我不确定我的做法是否正确。
我有两个类:Actor
和Building
。
这些类有一些子类:Policeman
、Fireman
、PoliceStation
和FireStation
。
我希望能够将所有这些项目放在一起,以便稍后迭代,因此我添加了一个基类:GameEntity
。
所以我现在有这个:
public abstract class GameEntity:
{
public GameEntity()
{
}
}
public class Actor: GameEntity
{
public int _speed;
public TileSprite _UI;
public Actor()
{
}
public bool CollidesWith(Vector2 pos)
{
//Do stuff here
}
public virtual void OnClick()
{
//Do stuff here
}
public void DoActing()
{
}
}
public class Policeman: Actor
{
public Policeman()
{
_speed = 10;
}
public override void OnClick()
{
//Do stuff
}
}
public class Building: GameEntity
{
public TileSprite _UI;
public Building()
{
}
public bool CollidesWith(Vector2 pos)
{
//Do stuff here
}
public virtual void OnClick()
{
//Do stuff here
}
public void DoBuilding()
{
}
}
public class PoliceStation: Building
{
public PoliceStation()
{
}
public override void OnClick()
{
//Do stuff
}
}
现在,我希望能够做到这一点:
List<GameEntity> Entities = new List<GameEntity>();
Actor a1 = new PoliceMan();
Building b1 = new PoliceStation
Entities.Add(a1);
Entities.Add(b1);
foreach(GameEntity ent in Entities)
{
if (ent.CollidesWith(something))
{
ent.OnClick();
//If Actor then do
ent.DoActing();
//If Building then do
ent.DoBuilding();
}
}
现在,为了完成最后一部分,我是不是最好实现一个包含
OnClick
和CollidesWith
的接口,还是可以用继承来完成?如果是,我该怎么做呢?祝好。