繁体   English   中英

类设计:将派生类添加到旧式继承层次结构中

[英]class design: add derived class to a legacy inheritance hierarchy

说我有

Class Base
{
    public void foo() //a public interface to user
    {
        doA();
        doB();
    }
    protected void doA(){...} //common implementation
    protected void doB(){} //type specific implementation
}
Class Derived1 extends Base
{
    int a,b,c,d,e,f,g; //bulky, clumsy implementation details specific to Derived1
    @Override
    protected void doB(){...} //implementation for Derived1
}
Class Derived2 extends Base
{
    @Override
    protected void doB(){...} //a different implementation for Derived2
}

如果我错了,请纠正我,这优于:

Class Derived1 extends Base
{
    int a,b,c,d,e,f,g; //bulky, clumsy implementation details specific to Derived1
    @Override
    protected void doA(){...} //move the common implementation to Derived1
    @Override
    protected void doB(){...} //implementation for Derived1
}
Class Derived2 extends Derived1
{
    @Override
    protected void doB(){...} //a different implementation for Derived2
}

因为后者将Derived1的内部公开给Derived2。

我的问题是,假设Derived1和Base来自现有的继承层次结构,而Derived1覆盖了doA()和doB()。 在不更改旧代码的情况下添加新的Derived2的最佳方法是什么?

由于Derived2与Derived1具有相同的doA()实现,因此我必须接受次等选择。 我考虑过组合,并将Derived1作为Derived2的成员,但是doA()受保护,因此我们无法从Derived2访问它。

非常感谢您的回复!

首先,我认为这是在你的问题中的错误:方法doAdoB被声明为private 子类无法访问其父级的私有方法,并且无法重写方法。

在您的例子,如果你调用Derived1.foo()Base.doA()将被调用。

您应该将它们声明为protected ,以便允许方法覆盖。

在这种情况下,我认为第二个选项是可以接受的,但这取决于实际代码。

Class Base
{
    public void foo() //a public interface to user
    {
        doA();
        doB();
    }
    protected void doA(){...} //common implementation
    protected void doB(){} //type specific implementation
}
Class Derived1 extends Base
{
    @Override
    protected void doB(){...} //implementation for Derived1
}
Class Derived2 extends Base
{
    @Override
    protected void doB(){...} //a different implementation for Derived2
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM