Mixin和接口实现

Mixin and interface implementation

本文关键字:实现 接口 Mixin      更新时间:2023-10-16

根据http://www.thinkbottomup.com.au/site/blog/C%20%20_Mixins_-_Reuse_through_inheritance_is_good

但请稍等,这些都无助于我们完成任务Manager框架,因为类不实现ITask接口。这就是最后一个Mixin的帮助所在——Mixin引入了ITask接口进入继承层次结构,充当适配器在某种类型的T和ITask接口之间:

template< class T >
class TaskAdapter : public ITask, public T
{
public:
    virtual void Execute()
    {
        T::Execute();
    }
    virtual std::string GetName()
    {
        return T::GetName();
    }
};

使用TaskAdapter很简单——它只是链中的另一个环节混合蛋白。

// typedef for our final class, inlcuding the TaskAdapter<> mixin
typedef public TaskAdapter< 
                    LoggingTask< 
                        TimingTask< 
                            MyTask > > > task;
// instance of our task - note that we are not forced into any heap allocations!
task t;
// implicit conversion to ITask* thanks to the TaskAdapter<>
ITask* it = &t;
it->Execute();

ITaskMyTask实现时,为什么需要TaskAdapter?此外,如果ITask不抽象,可能会导致钻石问题。

这是一篇非常有趣的文章。

在最后的Mixin示例中,MyTask类是从ITask派生的而不是。这意味着它不能被强制转换为ITask指针,这是在最后完成的。

在该示例中,我相信您可以从ITask导出MyTask。但我认为作者想说明,您甚至可以通过使用TaskAdapter来解耦MyTask类。