Implementing multiple interfaces in c++

前端 未结 4 1947
后悔当初
后悔当初 2020-11-28 15:43

I have the interface hierarchy as follows:

class A
{
public:
 void foo() = 0;
};

class B: public A
{
public:
void testB() = 0;
};

class C: public A
{
publi         


        
4条回答
  •  孤独总比滥情好
    2020-11-28 16:10

    I think what you are asking is, how do I create a second class hierarchy of implementations that mirrors my "interace" class hierarchy. You want to do this to reduce the coupling between your interface and implementations. Your problem is that you think your implementation classes should extend your interface classes but also the "natural" inheritance hierarchy in the impl classes, as in

       AImpl
      ^    ^
      |    |
    BImpl  CImpl
    

    I suggest you look at the GoF (Gang of Four) Bridge pattern that describes this pattern. Actuall, the example in the book is better than that on Wikipedia but can't seem to find it online. Here's a rough (ascii) UML:

    Window <>imp----------------------------> WindowImpl
    ^    ^                                    ^        ^
    |    |                                    |        |
    |   TransientWindow                       |     PMWindowImp
    IconWindow                              XWindowImp
    

    In the example above, you have a Window class whose #imp references the impementation. So, your IconWindow implementation will have #imp referencing, say XWindowIconWindow to perform the real work but clients will only ever reference it through the IconWindow instance. This reduces your recompile overhead.

    The salient points to make are:

    • Separate class hierarchy for window types (normal window, icon window, dialog) and window implementations (X-windows, PMWindows). They can be extended independently.
    • Operations are implemented in terms of abstract operations on WindowImp So, operations are abstracted from platform specifics.
    • Reduce prolieferation of classes that occurs if you try to mix the abstractions and multiple implementations.

    I'll leave it to you to translate this to your problem but comment if you have any trouble.

提交回复
热议问题