最近做了一段时间WPF,印象最深刻就是里面的mvvm模式,打算用C++做一个雏形,并为以后的项目做准备。
首先讲一下我对mvvm的理解(可能会有偏差,各位大佬可以指点),mvvm其实可以分开理解为 model , view ,viewmodel 。model提供数据模型,view就是ui,viewmodel做一些跟ui无关的逻辑(更新数据等),跟传统的mvc对比,control很难摆脱与view的耦合,比如更新ui元素等,长期下来,controler的代码只会越来越臃肿。mvvm是一套基于数据绑定的设计模式。C#本身就支持数据绑定机制,所以实现起来简单得多,但是C++也并非不能实现。
先讲一下设计思路
1. 维护一个全局的map来保存属性跟ui行为
2. UI创建的时候建立跟属性(代码里面的propertyName)的关系。
3. Model里面重载=号,在赋值以后,检索m_propertyAct以执行对应的UI更新函数(当然,后面可以设计成事件通知模式,以去除跟view的耦合)
4. Viewmodel里面只需要做一件事情,就是赋值!(是不是很爽有木有?这跟UI完全没有耦合关系)
下面贴上我写的一个雏形,以后有空再进行拓展
#include <iostream>
#include <functional>
#include <map>
//模拟数据绑定
const std::string propertyName = "txt";
std::map<std::string, std::function<void(std::string)>> m_propertyAct;
//假定这是一个UI元素
class UIElement
{
public:
explicit UIElement(std::string property) : _property(property)
{
m_propertyAct[property] = std::bind(&UIElement::SetTxt,this,std::placeholders::_1);
}
private:
std::string _property;
std::string _txt;
void SetTxt(std::string txt)
{
//这里可以做一些UI的行为
_txt = txt;
}
};
class Model
{
public:
Model(): _property(propertyName){}
void operator=(const Model& model)
{
m_propertyAct[_property](_param);
}
std::string _param;
private:
std::string _property;
};
class ViewModel
{
public :
ViewModel() {}
void DoSomething()
{
_model = Model();
}
private:
Model _model;
};
int main()
{
auto ui = UIElement(propertyName);
ViewModel().DoSomething();
std::cout << "Hello World!\n";
}