重构类层次结构的最佳方法 [英] Best Way to Refactor Class Hierarchy

查看:72
本文介绍了重构类层次结构的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 CGrandMother 有一个公共方法 virtual bool Compute() 这样做

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

virtual bool Compute()
{
    return false;
}

CGrandMother 公开派生CMother,它没有实现Compute.现在从 CMother 公开 C1C2 实现virtual bool Compute().现在 virtual bool C1::Compute()virtual bool C2::Compute() 分别做了很多适合于 C1C2,但也有很多与 CMother 相同的东西.现在有一个 CFamily 类,它的成员是一个指向 CMother 的指针,并且几乎在代码中的任何地方 Compute 都通过表单的行调用

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();

我如何才能找出与 C1C2 中完成的 CMother 相关的常见内容,以便我不必更改所有内容那些 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 ?

推荐答案

答案应该非常简单.你说很多与 CMother 相同的东西".因此,您应该将它们分解为 CMother 的成员函数.由于看起来只有从 CMother 派生的类需要该功能,您应该将新成员函数标记为受保护".@0x5453 所说的是一种方式;但我建议使用一个新函数,以便单独使用公共方法 CMother::Compute.可能还有一个 CMother 的子类没有实现 Compute 并且依赖 CMother::Compute 来做某些事情.

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.

这篇关于重构类层次结构的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆