簡體   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