OOP vs macro problem

前端 未结 7 1214

I came across this problem via a colleague today. He had a design for a front end system which goes like this:

class LWindow
{
   //Interface for common meth         


        
相关标签:
7条回答
  • 2021-01-04 13:29

    I would agree with you. Solution with WindowsCommonImpl macro is really bad. It is error-prone, hard to extend and very hard to debug. MFC is a good example of how you should not design your windows library. If it looks like MFC, you are really on a wrong way.

    So, your solution obviously better than macro-based one. Anyway, I wouldn't agree it is good enough. The most significant drawback to me is that you mix interface and implementation. Most practical value of separating interface and implementation is ability to easily write mock objects for testing purposes.

    Anyway, it seems the problem you are trying to solve is how to combine interface inheritance with implementation inheritance in C++. I would suggest using template class for window implementation.

    // Window interface
    class LWindow
    {
    };
    
    // ListBox interface (inherits Window interface)
    class LListBox : public LWindow
    {
    };    
    
    // Window implementation template
    template<class Interface>
    class WindowImpl : public Interface
    {
    };
    
    // Window implementation
    typedef WindowImpl<LWindow> Window;
    
    // ListBox implementation
    // (inherits both Window implementation and Window interface)
    class ListBox : public WindowImpl<LListBox>
    {
    };
    

    As I remember WTL windows library is based on the similar pattern of combining interfaces and implementations. I hope it helps.

    0 讨论(0)
提交回复
热议问题