我知道有菱形繼承被認爲是不好的做法。但是,我有兩個案例,我認爲鑽石繼承可以很好地適應。我想問,你會推薦我在這些情況下使用鑽石繼承,還是有另一種設計可能會更好。菱形繼承(C++)
案例1:我想在我的系統中創建代表不同類型「操作」的類。這些操作按幾個參數分類:
- 該操作可以是「讀取」或「寫入」。
- 動作可以是具有延遲或無延遲(它不僅是1點的參數,它顯著改變行爲)。
- 動作的「流量類型」可以是FlowA或FlowB。
我打算在具有以下設計:
// abstract classes
class Action
{
// methods relevant for all actions
};
class ActionRead : public virtual Action
{
// methods related to reading
};
class ActionWrite : public virtual Action
{
// methods related to writing
};
class ActionWithDelay : public virtual Action
{
// methods related to delay definition and handling
};
class ActionNoDelay : public virtual Action {/*...*/};
class ActionFlowA : public virtual Action {/*...*/};
class ActionFlowB : public virtual Action {/*...*/};
// concrete classes
class ActionFlowAReadWithDelay : public ActionFlowA, public ActionRead, public ActionWithDelay
{
// implementation of the full flow of a read command with delay that does Flow A.
};
class ActionFlowBReadWithDelay : public ActionFlowB, public ActionRead, public ActionWithDelay {/*...*/};
//...
當然,我會服從,沒有2個行動(從動作類繼承)將實施同樣的方法。
案例2:我在我的系統中實現了「Command」的組合設計模式。命令可以被讀取,寫入,刪除等。我也想要一系列命令,這些命令也可以被讀取,寫入,刪除等。一系列命令可以包含其他命令序列。
所以,我有如下設計:
class CommandAbstraction
{
CommandAbstraction(){};
~CommandAbstraction()=0;
void Read()=0;
void Write()=0;
void Restore()=0;
bool IsWritten() {/*implemented*/};
// and other implemented functions
};
class OneCommand : public virtual CommandAbstraction
{
// implement Read, Write, Restore
};
class CompositeCommand : public virtual CommandAbstraction
{
// implement Read, Write, Restore
};
另外,我有一種特殊的命令,「現代」的命令。一個命令和複合命令都可以是現代的。 「Modern」爲一個命令和複合命令添加了一定的屬性列表(兩者大都屬於相同的屬性)。我希望能夠持有指向CommandAbstraction的指針,並根據所需的命令類型對其進行初始化(通過新建)。所以,我要做到以下幾點設計(除了以上):
class ModernCommand : public virtual CommandAbstraction
{
~ModernCommand()=0;
void SetModernPropertyA(){/*...*/}
void ExecModernSomething(){/*...*/}
void ModernSomethingElse()=0;
};
class OneModernCommand : public OneCommand, public ModernCommand
{
void ModernSomethingElse() {/*...*/};
// ... few methods specific for OneModernCommand
};
class CompositeModernCommand : public CompositeCommand, public ModernCommand
{
void ModernSomethingElse() {/*...*/};
// ... few methods specific for CompositeModernCommand
};
而且,我將確保沒有2班從CommandAbstraction類繼承將實施同樣的方法。
謝謝。
嗨大衛。我有興趣學習高級OOP(繼承)主題,就像你在上面提到的帖子(函數,虛函數等)一樣。你可以推薦任何關於這個主題的書籍嗎? – 2010-10-19 13:01:50
@Carlo del Mundo:在這[問題]中有一本很好的書籍綱要(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)我特別喜歡閱讀Alexandrescu (不適合初學者)和Sutter。 – 2010-10-19 19:01:22