How would you refactor this polymorphic design in order to make it more flexible when adding new implementations?


I have a class that has many virtual functions that allows you to obtain references to interfaces. Clients using my API can implement my interfaces, then implement my top-level interface IMyInterface using their implementations.

My code then acts on their polymorphic IMyInterface implementation.

Here's some example code (not the real code, but you get the idea):

class MyImplementation : public IMyInterface


        virtual Interface1& get1()
            return impl1

        virtual Interface2& get2()
            return impl2;

        // etc...


        Impl1 impl1;

        Impl2 impl2;

        // etc...


I thought this design seemed really nice, but one day I wanted to change one of the implementations, but only one. In that case I had to rewrite the entire class and copy a lot of code.

There are actually 6 Impl objects, so I'd have to rewrite a class that has the exact same 5 Impl objects, but with one different.

Another problem is that people rely on this API design, so I need to keep the basics of it.

Is there a way to modify the design to make it more flexible, while still maintaining this API?


What I understand from your question:

If I understand correctly, you are wording with classes that are more or less and assembly of basic components, and you want to be able to exchange components with a minimum of coding.

Alternative 1: dynamic assembly

Why not opt them for a dynamic assembly at construction:

class MyBase : public IMyInterface

This video can help you solving your question :)
By: admin