MVC模式在日常软件设计中用得很多很多,本文以自动贩卖机为原型,以MVC模式进行设计。
类的声明:
sellor.h
#include <QString>
#include <QDebug>
//注意这里的前置声明要和后边的实现分开,否则会导致编译不通过
class SellerMOdel;
class SellerView;
//This is control
class SellerControl
{
public:
static SellerControl* getInstance();
void SetModle(SellerMOdel*);
void SetView(SellerView*);
void SellerControlHandleView(int goods_id);
private:
SellerControl();
~SellerControl();
static SellerControl* SellerInstance;
SellerMOdel* model;
SellerView* View;
};
//Model
class SellerMOdel
{
public:
SellerMOdel();
int getprice(int goods_id);
void update(int goods_id, int goods_num);
private:
int goods_num;
};
//View
class SellerView
{
public:
SellerView();
int SubGoodsID(int goodid);
void SetControl(SellerControl* ctrl);
void UpdateInfo(QString str);
private:
SellerControl* ctrl;
};
类的具体实现:
sellor.cpp
#include "sellor.h"
SellerControl* SellerControl::SellerInstance = NULL;
SellerControl::SellerControl()
{
qDebug() << "Seller Control init";
}
SellerControl::~SellerControl()
{
}
SellerControl* SellerControl::getInstance()
{
if(SellerControl::SellerInstance == NULL)
{
return new SellerControl();
} else {
return SellerControl::SellerInstance;
}
}
void SellerControl::SetModle(SellerMOdel* model)
{
if(model)
this->model = model;
}
void SellerControl::SetView(SellerView *view)
{
if(view)
this->View = view;
}
void SellerControl::SellerControlHandleView(int goods_id)
{
if (model)
{
int price = model->getprice(goods_id);
View->UpdateInfo(QString("goods_id is %1, price is %2").arg(goods_id).arg(price));
}
}
//Model
SellerMOdel::SellerMOdel()
{
qDebug()<< "Model init";
}
int SellerMOdel::getprice(int goods_id)
{
return 10;
}
void SellerMOdel::update(int goods_id, int goods_num)
{
qDebug()<<"goods_id:"<< goods_id;
qDebug()<<" goods_num:"<<goods_num;
}
//View
SellerView::SellerView()
{
qDebug()<<"View init";
}
int SellerView::SubGoodsID(int goodid)
{
if(ctrl)
{
ctrl->SetView(this);
ctrl->SellerControlHandleView(goodid);
}
}
void SellerView::SetControl(SellerControl* ctrl)
{
this->ctrl = ctrl;
}
void SellerView::UpdateInfo(QString str)
{
qDebug() << str;
}
测试代码:
int main(int argc, char *argv[])
{
SellerControl* ctrl = SellerControl::getInstance();
SellerView* view = new SellerView();
SellerMOdel* model = new SellerMOdel();
ctrl->SetModle(model);
view->SetControl(ctrl);
view->SubGoodsID(10);
}
版权声明:本文为k_wang_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。