如果您从基类覆盖方法并引入新功能,您是否违反SRP?

发布于 2025-02-01 15:54:20 字数 1295 浏览 2 评论 0原文

例如。

看看这个班级的层次结构:

public abstract class CharacterEquipment
{
    protected abstract void RunBeforeAttachProcedure();
    protected abstract void AttachToCharacter();
    protected abstract void PlayEquipEffects();

    public void Equip()
    {
        RunBeforeAttachProcedure();
        AttachToCharacter();
        PlayEquipEffects();
    }
}

public abstract class CharacterBackEquipment : CharacterEquipment
{
    protected override void AttachToCharacter()
    {
        // Attach procedure that never changes for the back.
    }
}

public class CharacterJetpack : CharacterBackEquipment
{
    protected override void RunBeforeAttachProcedure()
    {
        // Position jetpack so it is at the right position to attach to the character's back
        // There can be other equipments that you can attach to the character's back like a normal backpack which would need slightly different positioning and rotation
    }

    protected override void PlayEquipEffects()
    {
        // Play jetpack equip sounds and particle effects
    }

    public void ActivateThrusters(float force)
    {
        // This is new functionality introduced, now the equipped jetpack can fly
    }
}

这是否算作打破单一责任原则?就像在JetPack类中一样,即使功能是继承和OVERTINT,您也正在混合装备和飞行职责,对吗?

For example.

Look at this class hierarchy:

public abstract class CharacterEquipment
{
    protected abstract void RunBeforeAttachProcedure();
    protected abstract void AttachToCharacter();
    protected abstract void PlayEquipEffects();

    public void Equip()
    {
        RunBeforeAttachProcedure();
        AttachToCharacter();
        PlayEquipEffects();
    }
}

public abstract class CharacterBackEquipment : CharacterEquipment
{
    protected override void AttachToCharacter()
    {
        // Attach procedure that never changes for the back.
    }
}

public class CharacterJetpack : CharacterBackEquipment
{
    protected override void RunBeforeAttachProcedure()
    {
        // Position jetpack so it is at the right position to attach to the character's back
        // There can be other equipments that you can attach to the character's back like a normal backpack which would need slightly different positioning and rotation
    }

    protected override void PlayEquipEffects()
    {
        // Play jetpack equip sounds and particle effects
    }

    public void ActivateThrusters(float force)
    {
        // This is new functionality introduced, now the equipped jetpack can fly
    }
}

Does this count as breaking single responsibility principle? As in the jetpack class, even though functionality is inherited and ovewritten, you are mixing equipping and flying responsibilities, correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文