Difficulty:
Universal OBServer code implemented with C Template. This article is not mysterious, and Template is only used in the generalization of the status information type. Excessive details, there is no need to talk, I think everyone knows more than I know / *
Design Pattern IMPLEMENTATION WITH C Template - Observer
Author: jinhao
Data: 5 / JUL / 2004
* /
#ifndef _Observer_h_
#define _Observer_h_
#include
Template struct helper;
Template struct Subject;
Template Class Observer {Friend Class Helper ; protected: observer (): PSBJ_ (NULL) {} public: Virtual ~ Observer () {if (psbj_) psbj _-> Detach (* this);}
Virtual void Update (const msg &) = 0; private: Subject * psbj_;};
Template class subject {friend class helper ; public: virtual ~ subject () {typeName std :: vector *> :: item begin = obsvrvec_.begin (); Typename std :: Vector *> :: itrator end = obsvrvec_.end (); for (; begin! = end; begin) helper :: attachtosubject (null, * begin);} void attach (Observer & rhs) // register {obsvrvec_.push_back (& rhs); Helper :: attachtosubject (this, & rhs);
Void Detach (Observer & rhs) // unregister {typeName std :: vector *> :: iterator matched = Find (obsvrvec_.begin (), obsvrvec_.end (), & rhs); if ( Match! = obsvrvec_.end ()) obsvrvec_.rase (matched);} void notify () // notify all observers {typeName std :: vector *> :: iterator begin = obsvrvec_.begin (); TypeName Std :: Vector *> :: itrator end = obsvrvec_.end (); for (; begin! = end; begin) (* begin) -> Update (Message_);} protected: msg & message () {return message_;} const Msg & message () const {return message_;} void message (const Msg & rhs) {message_ = rhs;} private: Msg message_; std :: vector *> obsvrvec_; }; template struct helper {static void attachtosubject (Subject * sbj, observer * obsv) {OBSV-> psbj_ = sbj;}}; Endif // _ Observer_H_
The following is an example code Class ConcreteobServer1: Public Observer {public: void update (const string & message) {cout << message << endl;}};
class ConcreteObserver2: public observer {public: void update (const string & message) {copy (message.rbegin (), message.rend (), ostream_iterator (cout)); cout << endl; }};
Class ConcreteSubject: Public Subject {public: Void Set (Const String & Str) {Message (STR);}}