Best Way to Refactor Class Hierarchy

浪尽此生 提交于 2019-12-11 05:29:39

问题


I have a class CGrandMother having a public method virtual bool Compute() that does

virtual bool Compute()
{
    return false;
}

From CGrandMother derives publicly CMother which does not implement Compute. Now from CMother derive publicly C1 and C2 that do implement virtual bool Compute(). Now virtual bool C1::Compute() and virtual bool C2::Compute() respectively do a lot of stuff proper to respectively C1 and to C2, but also a lot of identical stuff proper to CMother. Now there's a class CFamily having as member a pointer to CMother and almost everywhere in the code Compute is called through lines of the form

ptrCMother->Compute();

How could I factor out the common stuff related to CMother done in C1 and C2 so that I wouldn't have to change all those ptrCMother->Compute(); lines ?


回答1:


The answer should be pretty straightforward. You said "a lot of identical stuff proper to CMother". So you should factor them out into a member function of CMother. Since it appears that the functionality is needed only by classes derived from CMother, you should mark the new member function "protected". What @0x5453 said is one way; but I'd suggest a new function, so as to leave the public method CMother::Compute alone. There could be another child class of CMother that does not implement Compute and relies on CMother::Compute to do certain things.



来源:https://stackoverflow.com/questions/40043292/best-way-to-refactor-class-hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!