2012-12-02 34 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。我认为扩展界面看起来是一个不错的选择。 –

相关问题