以前剛開始學習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
視圖部分在view.h中,代碼
//
// 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中代碼
//
// 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