Search code examples
design-patternsopen-closed-principle

How we can use OCP with delegation?


There are a lot samples of using OCP with help of inheritance. But I am confused how we can use OCP with delegation. Can anyone share any sample?


Solution

  • You can have a base class that delegates to a derived class as with the Template pattern. This is Open for extension by allowing derived classes, but the base class will still be closed to modification.

    Here's an example in C++:

    class BaseClass
    {
    public:
        void doStuff() {
            doStuff1(); // delegating to derived class
    
            // do base class stuff here
    
            doStuff2(); // delegating to derived class
    
            // do more base class stuff here
    
            doStuff3(); // delegating to derived class
        }
    
    protected:
        virtual void doStuff1() = 0;
        virtual void doStuff2() = 0;
        virtual void doStuff3() = 0;
    };
    
    class DerivedClass1 : public BaseClass
    {
    protected:
        void doStuff1() { /* your impl here */ }
        void doStuff2() { /* your impl here */ }
        void doStuff3() { /* your impl here */ }
    };
    
    // Implement as many other derived classes as you wish
    

    Notice you dont have to modify the BaseClass (its closed to mods) and it delegates to derived classes, and more derived classes could be implemented (open to extension)