如何在没有多个实例变量引用同一对象的情况下实现继承

本文关键字:对象 情况下 继承 实现 引用 变量 实例 | 更新日期: 2023-09-27 18:20:53

我觉得我应该只让一个实例变量引用一个对象。但在下面的代码中,我有两个引用同一对象的实例变量"_character"answers"_witch"。如果我添加一个更专业的witch类,我将不得不添加一个第三实例变量
在这种情况下,人们通常会这样做吗?或者有没有一种方法可以只使用一个参考来实现这一点?此外,我真的不想投任何东西(除非这真的是这个场景中的最佳实践)。

在WitchAnimationController扩展AnimationController的顶部,WitchState扩展CharacterState。

基本类:

public class AnimationController 
{
    protected CharacterState _character;
    public AnimationController( CharacterState character )
    {
        _character = character;
    }
    public void UpdateAnimations() 
    {
        /* call on some CharacterState functions... */
    }
}

儿童班:

public class WitchAnimationController : AnimationController
{
    protected WitchState _witch; //inherits from CharacterState
    public AnimationController( WitchState witch ) : base( witch ) 
    {
        _witch = witch;
    }
    public void UpdateAnimations() 
    {
        base.UpdateAnimations();
        /* call on some WitchState functions... */
    }
}

如何在没有多个实例变量引用同一对象的情况下实现继承

如果您不需要特定于交换机的调用,您可以放弃_witch字段并使用_character字段,尽管我个人会将其作为具有受保护属性的私有字段。

如果您需要特定于角色的成员,您应该考虑使动画控制器通用:

public class AnimationController<T> where T : CharacterState
{
    protected T _character;
    public AnimationController(T character)
    {
        _character = character;
    }
    public void UpdateAnimations() 
    {
        /* call on some CharacterState functions... */
    }
}

然后:

public class WitchAnimationController : AnimationController<WitchState>
{    
    public WitchAnimationController(WitchState witch) : base(witch) 
    {}
    public void UpdateAnimations() 
    {
        base.UpdateAnimations();
        _character.SomeMethodOnWitchState();
    }
}

_character.SomeMethodOnWitchState()调用将在WitchAnimationController内有效,因为_character实际上是WitchState类型。

您所拥有的并不可怕,但请考虑以下设计:

public class AnimationController 
{
    public AnimationController(  )
    {
    }
    public void UpdateAnimations( CharacterState character ) 
    {
        /* call on some CharacterState functions... */
    }
}
public class WitchAnimationController : AnimationController
{   
    public AnimationController( )
    {
    }
    public void UpdateAnimations(WitchState witch ) 
    {
        base.UpdateAnimations(witch );
        /* call on some WitchState functions... */
    }
}

可以保留所有引用,但如果控制器实际上只是在调用函数,则可以让其他人维护不同的状态对象。

任何一种方法都同样有效,没有更多信息(就像AnimationController的其他重要成员一样,我会采用我的方法。

使用泛型:

public class AnimationController<T> where T : CharacterState
{
    protected T _character;
    public AnimationController(CharacterState character)
    {
        _character = character;
    }
}

然后在每个祖先中,_character将是各自继承的类型,如下所示:

public class WitchAnimationController : AnimationController<WitchState>
{        
    public AnimationController(WitchState witch) : base(witch) 
    {
    }
}
相关文章: