让包含以下类层次结构的库:
- class LuaChunk
- {
- };
- class LuaExpr : public LuaChunk
- {
- };
- class LuaScript : public LuaChunk
- {
- };
现在我想通过扩展这两个类在我的应用程序中使用这个库:
- class AppLuaExpr : public LuaExpr
- {
- private:
- Foo * someAppSpecificMemberFoo;
- Bar * someAppSpecificMemberBar;
- };
- class AppLuaScript : public LuaScript
- {
- private:
- Foo * someAppSpecificMemberFoo;
- Bar * someAppSpecificMemberBar;
- };
这里的问题是,如果我有很多成员,每个成员都有自己的getter / setter对,那么它会产生大量的代码重复.
有没有办法,不使用多重继承(我想避免)将AppLuaExpr和AppLuaExpr中包含的特定于应用程序的东西放在一起?
我已经看过维基百科上列出的现有结构设计模式,但看起来似乎并没有适应我的问题.
谢谢.
解决方法
您可以将公共数据表示为他们自己的类,并在构造期间传递它.这样你就可以使用合成来封装所有内容.
- class Core { };
- class Component {
- int one,two;
- public:
- Component(int one,int two) : one(one),two(two)
- {}
- };
- class MobIoUs : public Core
- {
- Component c;
- public:
- MobIoUs(Component &c) : Core(),c(c) { }
- };
- class Widget : public Core
- {
- Component c;
- public:
- Widget(Component &c) : Core(),c(c)
- {}
- };
- int main(void)
- {
- Widget w(Component{1,2});
- MobIoUs m(Component{2,3});;
- return 0;
- }