lundi 7 novembre 2016

Pattern to Break Inheritance without affecting existing Behavior

I have classes with inherits from other classes. I am looking for pattern which will allow me to break this type of class to class inheritance and use Interface instead.

For example: Consider I have Base class and few derive classes as follows

Lib A :
class Base { ... }


Clients:
class Derived1 : public Base { ... }
class Derived2 : public Base { ... }
class Derived3 : public Derived2 { ... }

And clients uses objects of Base, Derived1, Derived2, Derived3.

I want to keep expose Base as interface. Such that,

Lib A will contain:
Interface IBase ( exposed )
and Class BaseImpl ( internal )

And clients will use
class Derived1 : public IBase { .. }
class Derived2 : public IBase { .. }
class Derived3 : public IBase { .. }

Now problem is, if I make changes as above, I will loose default implementation provided by BaseImpl here.

1 possible solution that I could think of is having factory as:

Lib A:

Interface IBase { ... }
class BaseImpl : public IBase { 
...
}
export static IBase* GetDefaultBase() 
{
   return new Base();
}

clients:

class Derived1 : public IBase
{

public:
 Derived1() { 
m_base = GetDefaultBase();
}

// and all implemented apis can use m_base to call default behavior provided by BaseImpl.

I dont see any issues with this approach. But I am curious to know, are there any well known pattern / solutions available for such refactoring problem?

Thanks, Kailas

Aucun commentaire:

Enregistrer un commentaire