mercredi 11 février 2015

OOP: How to dynamically extend functions in superclass

I have a base class B and 2 derived classes D1, D2.



class B {
int commonFunc();
virtual int specifyFunc();
}
class D1 : public B {
int specifyFunc();
}
class D2 : public B {
int specifyFunc();
}


Now I meet a requirement that i need to extend my base class function "commonFunc()". Since i don't want to modify existing code in base class, i derived another class like:



class B {
virtual int commonFunc(); // Change to virtual
virtual int specifyFunc();
}
class B2 : public B {
int commonFunc(); // A new commonFunc() to meet new requirement
}


However, D1 and D2 cannot use the new commonFunc() in B2 except I modify the inheritance hierarchy.


Here is a possible solution i figured out



class B {
virtual int commonFunc();
virtual int specifyFunc();
}
class D1 : public B {
int specifyFunc();
}
class D2 : public B {
int specifyFunc();
}
class NewD1 : public D1 {
int commonFunc(); // Overrided commonFunc() in base class
}
class NewD2 : public D2 {
int commonFunc(); // Overrided commonFunc() in base class
}


Since the commonFunc() in NewD1 and NewD2 are exactly the same, this solution involves a poor code-copy


I am looking for any design pattern or solution which can dynamically extend base class without much modification to existing class.


Aucun commentaire:

Enregistrer un commentaire