开发者

C#: Inheritance, Overriding, and Hiding

I'm having difficulty with an architectural decision for my C# XNA game.

The basic entity in the world, such as a tree, zombie, or the player, is represented as a GameObject. Each GameObject is composed of at least a GameObjectController, GameObjectModel, and GameObjectView.

These three are enough for simple entities, like inanimate trees or rocks. However, as I try to keep the functionality as factored out as possible, the inheritance begins to feel unwieldy. Syntactically, I'm not even sure how best to accomplish my goals.

Here is the GameObjectController:

public class GameObjectController
{
    protected GameObjectModel model;

    protected GameObjectView view;

    public GameObjectController(GameObjectManager gameObjectManager)
    {
        this.gameObjectManager = gameObjectManager;
        model = new GameObjectModel(this);
        view = new GameObjectView(this);
    }

    public GameObjectManager GameObjectManager
    {
        get
        {
            return gameObjectManager;
        }
    }

    public virtual GameObjectView View
    {
        get
        {
            return view;
        }
    }

    public virtual GameObjectModel Model
    {
        get
        {
            return model;
        }
    }

    public virtual void Update(long tick) 
    {
    }
}

I want to specify that each subclass of GameObjectController will have accessible at least a GameObjectView and GameObjectModel. If subclasses are fine using those classes, but perhaps are overriding for a more sophisticated Update() method, I don't want them to have to duplicate the code to produce those dependencies. So, the GameObjectController constructor sets those objects up.

However, some objects do want to override the model and view. This is where the trouble comes in.

Some objects need to fight, so they are CombatantGameObjects:

public class CombatantGameObject : GameObjectController
{
    protected new readonly CombatantGameModel model;
    public new virtual CombatantGameModel Model
    {
        get { return model; }
    }

    protected readonly CombatEngine combatEngine;

    public CombatantGameObject(GameObjectManager gameObjectManager, CombatEngine combatEngine)
        : base(gameObjectManager)
    {
        model = new CombatantGameModel(this);
        this.combatEngine = combatEngine;
    }

    public override void Update(long tick)
    {
        if (model.Health <= 0)
        {
            gameObjectManager.RemoveFromWorld(this);
        }
        base.Update(tick);
    }
}

Still pretty simple. Is my use of new to hide instance variables correct? Note that I'm assigning CombatantObjectController.model here, 开发者_如何学Pythoneven though GameObjectController.Model was already set. And, combatants don't need any special view functionality, so they leave GameObjectController.View alone.

Then I get down to the PlayerController, at which a bug is found.

public class PlayerController : CombatantGameObject
{
    private readonly IInputReader inputReader;

    private new readonly PlayerModel model;
    public new PlayerModel Model
    {
        get { return model; }
    }

    private float lastInventoryIndexAt;
    private float lastThrowAt;

    public PlayerController(GameObjectManager gameObjectManager, IInputReader inputReader, CombatEngine combatEngine)
        : base(gameObjectManager, combatEngine)
    {
        this.inputReader = inputReader;
        model = new PlayerModel(this);
        Model.Health = Constants.PLAYER_HEALTH;
    }

    public override void Update(long tick)
    {
        if (Model.Health <= 0)
        {
            gameObjectManager.RemoveFromWorld(this);
            for (int i = 0; i < 10; i++)
            {
                Debug.WriteLine("YOU DEAD SON!!!");
            }
            return;
        }

        UpdateFromInput(tick);
        // ....
    }
   }

The first time that this line is executed, I get a null reference exception:

model.Body.ApplyImpulse(movementImpulse, model.Position);

model.Position looks at model.Body, which is null.

This is a function that initializes GameObjects before they are deployed into the world:

   public void Initialize(GameObjectController controller, IDictionary<string, string> data, WorldState worldState)
    {
        controller.View.read(data);
        controller.View.createSpriteAnimations(data, _assets);

        controller.Model.read(data);

        SetUpPhysics(controller,
         worldState,
         controller.Model.BoundingCircleRadius,
         Single.Parse(data["x"]),
         Single.Parse(data["y"]), bool.Parse(data["isBullet"]));
    }

Every object is passed as a GameObjectController. Does that mean that if the object is really a PlayerController, controller.Model will refer to the base's GameObjectModel and not the PlayerController's overriden PlayerObjectModel?

In response to rh:

This means that now for a PlayerModel p, p.Model is not equivalent to ((CombatantGameObject)p).Model, and also not equivalent to ((GameObjectController)p).Model.

That is exactly what I do not want. I want:

PlayerController p;
p.Model == ((CombatantGameObject)p).Model
p.Model == ((GameObjectController)p).Model

How can I do this? override?


The key lies in your use of the 'new' keyword here:

private new readonly PlayerModel model;
public new PlayerModel Model
{
    get { return model; }
}

and here:

protected new readonly CombatantGameModel model;
public new virtual CombatantGameModel Model
{
    get { return model; }
}

What you are saying is: "I know my base class already defined these, but I want to define different ones that happen to have the same name."

This means that now for a PlayerModel p, p.Model is not equivalent to ((CombatantGameObject)p).Model, and also not equivalent to ((GameObjectController)p).Model.

Here are a couple ways you could proceed.

1) Do not offer strongly-typed child properties. I know this probably sounds bad at first, but it is actually a very powerful concept. If your base model defines the appropriate abstract/virtual methods that are suitable for all subclasses, you can define the property once in the base class and be done. Subclasses then can provide their own implementation.

Here is one possible way to implement this.

public class GameObjectController /* ... */
{
    /* ... */
    public GameObjectController()
    {
        Model = new GameObjectModel(this);
    }

    public GameObjectModel Model { get; protected set; }
}

public class CombatantGameObject : GameObjectController
{
    /* ... */
    public CombatantGameObject()
    {
        Model = new CombatantModel(this);
    }
}
/* ... */

2) Offer strongly typed properties when accessed through subclasses, but store the field once in the base class.

This can work, but it is tricky to do correctly. It wouldn't be my first choice.

public class GameObjectController /* ... */
{
    /* ... */
    public GameObjectController()
    {
        Model = new GameObjectModel(this);
    }

    public GameObjectModel Model { get; protected set; }
}

public class CombatantGameObject : GameObjectController
{
    /* ... */
    public CombatantGameObject()
    {
        Model = new CombatantModel(this);
    }

    public new CombatantModel Model
    {
        get
        {
            return (CombatantModel)base.Model;
        }
        protected set
        {
            base.Model = value;
        }
    }
}
/* ... */

Also, be wary about over-committing to a complex object model too early. Sometimes starting simple, and refactoring aggressively, is the best way to get a good model that reflects how your code actually ends up working.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜