2011-08-26 52 views
0

考慮以下2種方法:OO繼承問題

class A{ 
    void Method1(){ 
    if(!something) return; 
    DoX(); 
    DoY(); 

    DoZ(); 
} 
class B{ 
    void Method2(){ 
    if(!something) return; 
    DoX(); 
    DoY(); 

    DoP(); 
    } 
} 

顯然是一個超類可以寫,以避免乾燥原理:

class Super{ 
    virtual void Method(){ 
    if(!something) return; //problem... 
    DoX(); 
    DoY(); 
    } 
} 
class A:Super{ 
    override void Method(){ 
    inherited Method(); 
    DoZ(); 
    } 
} 
class B:Super{ 
    override void Method(){ 
    inherited Method(); 
    DoP(); 
    } 
} 

的問題是什麼檢查哪裏會跑!在第一個例子中,在第二個例子中,它將超出超類的方法,但在派生類中執行DoZ()或DoP();

我的問題:解決這類問題的最好方法是什麼?這使我手中的一個正在父類的方法,返回布爾

virtual bool Method(){ if(!something) return false;} 

override bool Method(){ if(!inherited Method()) return;} 

這是最好的解決辦法的功能?

回答

0

爲什麼不爲DoP或Doz聲明另一個虛擬方法,如果您想讓它們公開並保留它們各自的名稱,可以將它們包裝起來。

像超:

virtual void wrapping(){}; 

然後每個孩子:

void wrapping() { DoP(); } 
void wrapping() { DoZ(); } 

不知道我已經清楚了。

0

另一種選擇:保留派生方法中的檢查。也許派生類可能需要稍微不同的條件?

class Super{ 
    virtual void Method(){ 
    DoX(); 
    DoY(); 
    } 
} 
class A:Super{ 
    override void Method(){ 
    if(!something) return; 
    inherited Method(); 
    DoZ(); 
    } 
} 
class B:Super{ 
    override void Method(){ 
    if(!something) return; 
    inherited Method(); 
    DoP(); 
    } 
} 
1

如何:

class Super { 
    void Method() { 
     if (!something) return; 

     DoX(); 
     DoY(); 

     DoThingy(); 
    } 

    abstract void DoThingy(); 
} 

class A : Super { 
    override DoThingy() { 
     DoZ(); 
    } 
} 

class B : Super { 
    override DoThingy() { 
     DoP(); 
    } 
}