class gadget {\fbox{gadget}
public: virtual void request(window* w)=0; virtual void draw()=0; };
class window {\fbox{window}
gadget* g; public: window(gadget* p) : g(p) { g->request(this); } void allocate(int x1, int y1, int x2, int y2) { ... } void damage() { g->draw(); } };
class button : public gadget {\fbox{item}
public: button( int x, int y ) : _x(x), _y(y) {} void request(window* w) { _w = w; w->allocate(_x , _y, _x + 20, _y + 15); } void draw() { w->rectangle(_x , _y, _x + 20, _y + 15); } private: int _x; int _y; window* _w; };
gadget* b = new button(100,200); window* w = new window(b); w->damage();
class event {\fbox{event}
int _info; public: event(int i) : _info(i) { } int info() { return _info; } };
class handler {\fbox{handler}
event* e; public: handler(event* p) : e(p) { g = 0; } virtual ~handler() { delete e; } int info() { return e->info(); } void set(gadget* p ) { g = p; } virtual void operator()() { if (g) g->callback(); } protected: gadget* g; };
class gadget {\fbox{gadget}
public: enum { PRESS, RELEASE }; gadget(int i) : info(i) { next = 0; } void pick(handler* h) { if (h->info() == info) { h->set( this ); } else if (next) next->pick(h); } virtual void callback() = 0; void insert(gadget* g); private: int info; gadget* next; }; void gadget::insert(gadget* g) { if (!next) next = g; else next->insert(g); }
class button : public gadget {\c{\fbox{button}}
public: button() : gadget(PRESS) { } void callback() { cout << "..."; } };
class window {\fbox{window}
public: window(gadget* p) { g = p; } void insert(gadget* p) { g->insert(p); } void receive(event* e) { handler* h = new handler(e); g->pick(h); (*h)(); } private: gadget* g; };
template< class T > class model {\fbox{model}
public: void tell(view* v) { dependent = v; } one view only
void changed() { if (dependent) dependent->update(); } virtual T value()=0; protected: view* dependent; model() { dependent = 0; } restricted creation
};
template< class T > class view {\fbox{view}
public: view(model* p) { p->tell(this); m = p; } virtual void update() { cout << m->value() << endl; or whatever
} protected: model* m; };
class account : public model{ int n; public: account() { n = 0; } void operator++() { n++; changed(); } int value() { return n; } };
account
account a; viewv(&a); a++; a++;