1. 程式人生 > >MVC 模式淺析(C++版demo)

MVC 模式淺析(C++版demo)

網上很少關於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;
};