如何在不使用多继承的情况下兼具两个Actor子类的功能
解决方案:规避多继承实现类功能合并
问题背景
现有类结构如下:
class Actor:public Base , public ISomething... { ... virtual void PreComponent(); virtual void PostComponent(); }; class ModularActor:public Actor { ... virtual void PreComponent() override { Actor::PreComponent(); ... }; virtual void PostComponent() override { ... Actor::PostComponent(); }; }; class GenActor:public Actor , public ISomething2... { ... void Func1(); void Func2(); void Func3(); };
需要实现自定义MyActor,同时拥有ModularActor的PreComponent/PostComponent逻辑、GenActor的Func1/Func2/Func3功能,但项目禁止多继承,且不希望复制代码。
方案1:组合+方法转发
通过在MyActor中持有ModularActor和GenActor的实例,将对应方法转发给它们,同时直接继承Actor。
代码实现
class MyActor : public Actor { private: ModularActor modularImpl; GenActor genImpl; public: // 转发ModularActor的生命周期方法 void PreComponent() override { modularImpl.PreComponent(); } void PostComponent() override { modularImpl.PostComponent(); } // 转发GenActor的功能方法 void Func1() { genImpl.Func1(); } void Func2() { genImpl.Func2(); } void Func3() { genImpl.Func3(); } // 继承Actor的原生功能 // ... };
注意:如果
ModularActor或GenActor构造需要依赖Actor上下文,可将MyActor的构造参数传递给成员实例,或改用智能指针延迟初始化。
方案2:提取功能到独立工具类
将ModularActor和GenActor的核心逻辑从继承结构中剥离,封装成独立工具类,MyActor直接调用这些工具类的方法。
代码实现
// 提取ModularActor的生命周期逻辑 class ModularLogic { public: static void RunPreComponent(Actor* owner) { owner->Actor::PreComponent(); // 原ModularActor的额外逻辑 ... } static void RunPostComponent(Actor* owner) { // 原ModularActor的额外逻辑 ... owner->Actor::PostComponent(); } }; // 提取GenActor的功能逻辑 class GenLogic { public: void Func1() { /* 原GenActor的Func1逻辑 */ } void Func2() { /* 原GenActor的Func2逻辑 */ } void Func3() { /* 原GenActor的Func3逻辑 */ } }; class MyActor : public Actor { private: GenLogic genLogic; public: void PreComponent() override { ModularLogic::RunPreComponent(this); } void PostComponent() override { ModularLogic::RunPostComponent(this); } void Func1() { genLogic.Func1(); } void Func2() { genLogic.Func2(); } void Func3() { genLogic.Func3(); } };
此方式彻底摆脱继承依赖,用组合调用实现逻辑复用。
方案3:继承ModularActor+组合GenActor
如果允许MyActor直接继承ModularActor,则可自动获得其生命周期方法,仅通过组合GenActor复用功能方法。
代码实现
class MyActor : public ModularActor { private: GenActor genActor; public: // 直接继承ModularActor的PreComponent/PostComponent,无需重写 // 适配GenActor的功能方法 void Func1() { genActor.Func1(); } void Func2() { genActor.Func2(); } void Func3() { genActor.Func3(); } // 继承Actor和ModularActor的其他功能 // ... };
这是最简洁的方案,最大化利用已有继承结构,仅补充缺失的功能模块。
内容的提问来源于stack exchange,提问作者yaww x
相关产品推荐
相关产品推荐

