重点:
1.presenter里面包含view和model
2.和MVC不同的是View和Model之间不进行交互
3.view包含presenter,view通过presenter反向处理逻辑。
链接:
MVP简单实现_安卓mvp presenter-CSDN博客
Model.h
#pragma once
//Model数据处理器
class Model
{
public:void Increace(){count++;}void Decreace(){count--;}int GetCount(){return count;}void SetCount(int num){count = num;}
private:int count{ 10 };
};
View.h
#pragma onceusing namespace std;
//view显示器
class CounterPresenter;
class View
{
public:void Update(int data){cout << data << endl;}void SetPresenter(weak_ptr<CounterPresenter> pre){m_presenter = pre;}void IncreaceView();void DecreaceView();
private:weak_ptr<CounterPresenter> m_presenter;
};
view.cpp
#include "CView.h"
#include "CCounterPresenter.h"
//view显示器
void View::IncreaceView()
{if (std::shared_ptr<CounterPresenter> locked = m_presenter.lock()){locked->HandleIncrementPressed();}
}
void View::DecreaceView()
{if (std::shared_ptr<CounterPresenter> locked = m_presenter.lock()){locked->HandleDecrementPressed();}
}
CounterPresenter.h
#pragma once#include "CModel.h"
#include "CView.h"
using namespace std;
//Controller控制器
class CounterPresenter
{
public:CounterPresenter(shared_ptr<Model> model, shared_ptr<View> view) :m_model(model), m_view(view){}void HandleIncrementPressed(){m_model->Increace();m_view->Update(m_model->GetCount());}void HandleDecrementPressed(){m_model->Decreace();m_view->Update(m_model->GetCount());}
private:shared_ptr<Model> m_model;shared_ptr<View> m_view;
};
test.cpp
// Test.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//#include <iostream>
#include <vector>
#include "CModel.h"
#include "CView.h"
#include "CCounterPresenter.h"using namespace std;int main()
{shared_ptr<Model> model= make_shared<Model>();shared_ptr<View> view = make_shared<View>();shared_ptr<CounterPresenter> cont = make_shared<CounterPresenter>(model, view);view->SetPresenter(cont);view->IncreaceView();view->DecreaceView();return 0;}