2012-12-02 29 views
0
class IInterfaceTest 
{ 
    virtual void AddProperty(string key, string value) = 0; 
    virtual void DoStuff(randomObject obj) = 0; 
    ... 
    //More pure virtual methods 

} 

class Concrete1 : public IInterfaceTest 
{ 
    void AddProperty(string key, string value) 
    { 
     //Implementation 
    } 
    void DoStuff(randomObject obj) 
    { 
     //Implementation 
    } 

    //Implements the other pure virtual methods 
} 

class Concrete2 : IInterfaceTest 
{ 
    void AddProperty(string key, string value) 
    { 
     //Implementation 
    } 
    void DoStuff(randomObject obj) 
    { 
     //Implementation 
    } 

    //Implements the other pure virtual methods 
    //PLUS adds its own 

    void FindProperty(string key) 
    { 
     //Implementation 
    } 
} 

的我有某處方法,它採用這個接口作爲參數:這是一個設計不好的界面嗎?

class RandomClass 
{ 
    void DoRandomStuff(IInterfaceTest* rnd) 
    { 
     //Problem is i cannot do: 
     //rnd->FindProperty("val2"); 

     //I have to do this: 
     Concrete2* con2 = dynamic_cast<Concrete2*>(rnd); 
    } 
} 

它有點帶走接口的美麗?

+1

也許你應該讓'RandomClass :: DoRandomStuff'只接受'Concrete2'實例。 –

+0

爲什麼你找不到房產?對我來說沒有意義,可以設置屬性,但不能通過抽象接口檢索。 – StoryTeller

+0

@DimaRudnik實際使用情況稍微複雜一些。實際問題與此密切相關。 –

回答

4

問題不是接口,問題是RandomClass::DoRandomStuff當它實際上需要更具體的東西時接受廣義對象。

也許你不想接受Concrete2類型的對象,但希望允許將來擴展。然後添加另一個抽象類:

class IInterfaceTest2 : public IInterfaceTest 
{ 
    virtual void FindProperty(string key) = 0; 
}; 

class Concrete2 : IInterfaceTest2 
{ 
    .... 
}; 
+0

有道理......我提出了兩個版本,一個採用具體類型或使用dynamic_cast。我認爲擴展界面看起來是一個不錯的選擇。 –

相關問題