如何关联不同名称的重复代码实现?以C++的getWindowTitle与getText方法为例
实现复用的几种常见方案
根据你的业务场景可以选择以下不同的实现方式:
方案1:抽取公共逻辑为独立工具函数
耦合度最低,适合重复逻辑完全不依赖Window或Button的内部成员状态的场景:
#include <iostream> using namespace std; // 抽离公共逻辑 void printCommonText() { cout << "Text"; } class Window { public: Window(); void getWindowTitle() { printCommonText(); } }; class Button { public: Button(); void getText() { printCommonText(); } };
方案2:Button类关联Window实例指针/引用
适合getWindowTitle逻辑依赖Window内部成员状态,且Button的getText需要绑定某一个具体Window实例的场景:
#include <iostream> using namespace std; class Window { public: Window(); void getWindowTitle() { cout << "Text"; // 即便用到Window的私有成员变量也能正常运行 } }; class Button { private: Window* associatedWindow; public: // 构造时传入要关联的Window实例 Button(Window* w): associatedWindow(w) {} void getText() { associatedWindow->getWindowTitle(); } };
方案3:继承公共基类
适合Window和Button本身业务上属于同类型UI组件,有大量公共属性/行为的场景:
#include <iostream> using namespace std; // 抽离公共基类 class BaseUI { protected: void commonPrint() { cout << "Text"; } }; class Window : public BaseUI { public: Window(); void getWindowTitle() { commonPrint(); } }; class Button : public BaseUI { public: Button(); void getText() { commonPrint(); } };
内容的提问来源于stack exchange,提问作者david
相关产品推荐
相关产品推荐

