Skip to content

Instantly share code, notes, and snippets.

@kyle-go
Last active December 15, 2015 11:29
Show Gist options
  • Save kyle-go/5253278 to your computer and use it in GitHub Desktop.
Save kyle-go/5253278 to your computer and use it in GitHub Desktop.
c++ mvc model.... compile with vs2008
#ifndef MVC_H_
#define MVC_H_
#include <set>
#include <list>
#include <memory>
#include <functional>
template <typename T>
class observer
{
public:
typedef std::tr1::function<bool(const T&)> CB_FUNCTION;
observer(typename CB_FUNCTION callback):callback_(callback){};
virtual const T calc() const = 0;
void ApplyModel(const T& t) const
{
callback_(t);
}
private:
typename CB_FUNCTION callback_;
};
template <typename T>
class model
{
public:
~model()
{
std::set<observer<T>*>::iterator it = observer_.begin();
for (;it!=observer_.end(); it++) {
delete *it;
}
}
void add_observer(observer<T>* o)
{
//if the o is already exist, just do nothing.
std::set<observer<T>*>::iterator it = observer_.find(o);
if (it != observer_.end())
return;
observer_.insert(o);
fresh();
}
void remove_observer(observer<T>* o)
{
observer_.erase(o);
}
void fresh()
{
std::set<observer<T>*>::iterator it = observer_.begin();
const T d = (*it)->calc();
for (; it!=observer_.end(); it++) {
(*it)->ApplyModel(d);
}
}
protected:
model(){};
private:
model(const model&);
void operator=(const model&);
std::set<observer<T>*> observer_;
};
#endif //MVC_H_
#include <memory>
#include <functional>
#include <windows.h>
#include <stdio.h>
#include "mvc.h"
class GameModel : public model<int>
{
public:
static std::tr1::shared_ptr<GameModel> SingleInstance() {
static std::tr1::shared_ptr<GameModel> p(new GameModel);
return p;
}
//some other public functions...
private:
//some data...
//...
//make sure this class is a single instance.
GameModel(){};
GameModel(const GameModel&);
void operator=(const GameModel&);
};
class GameObserver : public observer<int>
{
public:
static GameObserver* factory(CB_FUNCTION c)
{
return new GameObserver(c);
}
virtual const int calc() const
{
std::tr1::shared_ptr<GameModel> model_int = GameModel::SingleInstance();
//do some calc with model_int...
//...
return 9;
}
private:
GameObserver(CB_FUNCTION callback):observer(callback){}
};
//this is a callback function
bool cb_function(const int& i)
{
printf("this is cb_function, i=%d\n", i);
return true;
}
int main()
{
std::tr1::shared_ptr<GameModel> gm = GameModel::SingleInstance();
GameObserver* go = GameObserver::factory(cb_function);
gm->add_observer(go);
gm->add_observer(go);
gm->add_observer(GameObserver::factory(cb_function));
gm->fresh();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment