Possibility to mix composite pattern and curiously recurring template pattern

前端 未结 3 1498
既然无缘
既然无缘 2021-01-17 14:00

I have a composite pattern implementation, used for GUI components:

class CObject {
private:

  CObject * m_pParent;  
  CObjectContainer * m_pChildren;

  v         


        
3条回答
  •  青春惊慌失措
    2021-01-17 14:51

    You can add one level of abstraction:

    class CObjectBase
    {
        public:
            // Other methods...
            virtual CObjectBase* detach() = 0;
            virtual CObjectBase* duplicate() const = 0;
    };
    
    template 
    class CObject : public CObjectBase
    {
        public:
            // ...
            Child* duplicate() const
            {
                return new Child(*static_cast(this));
            }
    
            Child* detach()
            {
                m_pParent->RemoveChild(this);
                m_pParent = nullptr;
                return static_cast(this); // Cast needed here (inherent to CRTP)
            }
            std::vector children; // Array possible now
            // ...
    };
    
    class MyObject : public CObject
    {
        // ...
    };
    

    In natural language: an interface for all objects (CObjectBase) have a partial implementation for its descendants (CObject), which just have to inherit this partial implementation, decreasing the amount of replicated code.

提交回复
热议问题