以前刚开始学习C++时候,觉得多重继承完全没有必要。伤脑筋,处理不好。最后1个类会继承N多父亲类处理。
晚上看django资料时候。发现django的cbv(class base view)是使用多重集成的。
分为mixin与view部分。
子类化view时候,通过继承自定义的mixin来处理参数过滤。瞬间想到这其实是一种插件机制。也可以说实现了mvc的部分分离。
网上找了一下C++的多重继承资料,基本都在讲多重继承的语法。
用C++来实现下。
逻辑处理部分logic.h中
// // Logic.h // MultipleInheritance // // Created by 王 岩 on 13-8-23. // Copyright (c) 2013年 王 岩. All rights reserved. // #ifndef MultipleInheritance_Logic_h #define MultipleInheritance_Logic_h class Mixin { protected: int m_data; public: virtual void setParam() { m_data = 10; } virtual int getParam() { return m_data; } }; #endif
// // Render.h // MultipleInheritance // // Created by 王 岩 on 13-8-23. // Copyright (c) 2013年 王 岩. All rights reserved. // #ifndef MultipleInheritance_Render_h #define MultipleInheritance_Render_h #include "views.h" #include <string> class Render { public: static void RenderView( std::string templateName, int data ) { std::cout << "i come from view: " << templateName << "\ni come from data: "<< data << std::endl; } }; #endif
// // views.h // MultipleInheritance // // Created by 王 岩 on 13-8-23. // Copyright (c) 2013年 王 岩. All rights reserved. // #ifndef MultipleInheritance_views_h #define MultipleInheritance_views_h #include "Logic.h" #include "Render.h" #include <iostream> #include <string> class View { protected: std::string m_template; public: virtual void Render() = 0; virtual std::string getTemplateName() { return this->m_template; } virtual void setTemplateName(std::string sName) { this->m_template = sName; } void as_View() { this->Render(); } }; class getView : virtual public Mixin , virtual public View { void Render() { this->setParam(); //这里修改为多各种参数 //参数1,html模版 //后续参数为字典 Render::RenderView( this->getTemplateName() , this->m_data); } }; #endif
// // main.cpp // MultipleInheritance // // Created by 王 岩 on 13-8-23. // Copyright (c) 2013年 王 岩. All rights reserved. // #include <iostream> #include "views.h" class subMixin : virtual public Mixin { public: void setParam() { m_data = 100; } }; class subGetView : virtual public subMixin , virtual public getView { public: subGetView() { this->setTemplateName( "hello.world" ); } }; int main(int argc, const char * argv[]) { // insert code here... subGetView *sView = new subGetView(); sView->as_View(); return 0; }
i come from view: hello.world i come from data: 100