Mixin和接口实现
Mixin and interface implementation
根据http://www.thinkbottomup.com.au/site/blog/C%20%20_Mixins_-_Reuse_through_inheritance_is_good
But hang on a minute, none of this helps us plug into our Task
Manager framework as the classes do not implement the ITask interface.
This is where one final Mixin helps - a Mixin which introduces the
ITask interface into the inheritance hierarchy, acting as an adapter
between some type T and the ITask interface:
template< class T >
class TaskAdapter : public ITask, public T
{
public:
virtual void Execute()
{
T::Execute();
}
virtual std::string GetName()
{
return T::GetName();
}
};
Using the TaskAdapter is simple - it's just another link in the chain
of mixins.
// 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();
当 ITask
由 MyTask
实现时,为什么需要 TaskAdapter
?另外如果ITask
不是抽象的,可能会导致菱形问题。
那是一篇非常很酷很有趣的文章。
在最后一个 Mixin 示例中,MyTask
class 是 而不是 从 ITask
派生的。这意味着它不能转换为在最后完成的 ITask
指针。
在那个例子中,我相信你可以从 ITask
推导出 MyTask
。但我认为作者想说明您甚至可以使用 TaskAdapter
.
解耦 MyTask
class
根据http://www.thinkbottomup.com.au/site/blog/C%20%20_Mixins_-_Reuse_through_inheritance_is_good
But hang on a minute, none of this helps us plug into our Task Manager framework as the classes do not implement the ITask interface. This is where one final Mixin helps - a Mixin which introduces the ITask interface into the inheritance hierarchy, acting as an adapter between some type T and the ITask interface:
template< class T > class TaskAdapter : public ITask, public T { public: virtual void Execute() { T::Execute(); } virtual std::string GetName() { return T::GetName(); } };
Using the TaskAdapter is simple - it's just another link in the chain of mixins.
// 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();
当 ITask
由 MyTask
实现时,为什么需要 TaskAdapter
?另外如果ITask
不是抽象的,可能会导致菱形问题。
那是一篇非常很酷很有趣的文章。
在最后一个 Mixin 示例中,MyTask
class 是 而不是 从 ITask
派生的。这意味着它不能转换为在最后完成的 ITask
指针。
在那个例子中,我相信你可以从 ITask
推导出 MyTask
。但我认为作者想说明您甚至可以使用 TaskAdapter
.
MyTask
class