网上很少关于C++有关的MVC模式解析,所以最近闲来无事,写了个简单的demo:
// mvc_test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "mvc_model.h"
#include <string>
#include <iostream>
class MVC_View : public MVC_Controller
{
public:
MVC_View()
{
m_CalcModel.setController(this);
}
void onGetResultButtonClick()
{
m_CalcModel.setValueA("hello ");
m_CalcModel.setValueB("world!");
m_CalcModel.getResult();
}
virtual void updateResult(std::string strResult)
{
m_strResult = strResult;
std::cout << m_strResult.c_str() << std::endl;
}
private:
MVC_Model m_CalcModel;
std::string m_strInputA;
std::string m_strInputB;
std::string m_strResult;
};
int _tmain(int argc, _TCHAR* argv[])
{
MVC_View _test;
return 0;
}
mvc_controller.h
#include <string>
class MVC_Controller
{
public:
virtual void updateResult(std::string strResult) = 0;
};
mvc_model.h
#pragma once
#include "mvc_controller.h"
#include <string>
class MVC_Model
{
public:
MVC_Model(void)
: m_pCalcController(NULL){
}
~MVC_Model(void){
}
void setController(MVC_Controller *cb){
m_pCalcController = cb;
}
void setValueA(std::string str){m_strA = str;}
std::string getValueA(){return m_strA;}
void setValueB(std::string str){m_strB = str;}
std::string getValueB(){return m_strB;}
void setResult(std::string str){m_strResult = str;}
void getResult(){
m_strResult = m_strA + m_strB;
if (m_pCalcController)
{
m_pCalcController->updateResult(m_strResult);
}
}
private:
MVC_Controller *m_pCalcController;
std::string m_strA;
std::string m_strB;
std::string m_strResult;
};