Data Sinks or Observers
The Observer class is illustrated in Listing 6. It contains a protected constructor and a virtual Update() member function. Derived classes implement Update() to refresh the view set up by the observer.
Listing 6 Base Observer Class
class Observer { public: virtual void Update(Subject* theChangedSubject) = 0; protected: Observer() { }; };
The constructor is protected so that derived classes can access it if required. You finally see the observer implemented as the class NetOperationViewer in Listing 7.
Listing 7 Observer Class
class NetOperationViewer : public Observer { public: NetOperationViewer(OperationList*); virtual ~NetOperationViewer(); virtual void Update(Subject*); virtual void Draw(); private: OperationList* _subject; };
The constructor for NetOperationViewer is seen in Listing 8. This function takes a pointer to a subject (in this case, an OperatonList) and attaches it to the list supported by the subject.
Listing 8 Observer Constructor
NetOperationViewer::NetOperationViewer(OperationList* s) { subject = s; subject->Attach(this); printf("Hello from observer\n"); }
The destructor does the reverse, i.e., it detaches the observer. The Update() and Draw() member functions merely refresh and display the current operation.
Our second observer is interested only in the percent completion of the network operation, which is provided by a class called NetOperationPercentViewer. This class has similar semantics to the other observer (NetOperationViewer).