Data Source or Subject
Listing 2 illustrates an excerpt from subject.cpp—this is the Subject class, the container of the data of interest to the observers.
Listing 2 Subject Class that Provides Access to the Data
class Subject { public: virtual ~Subject() { }; virtual void Attach(Observer*); virtual void Detach(Observer*); virtual void Notify(); protected: Subject() { }; private: list<Observer*> _observers; };
This class contains a virtual destructor, three virtual member functions, and a protected constructor. The member functions allow observers to:
- Gain access (i.e., attach) to the subject data
- Remove access (i.e., detach) to the subject data
- Receive notification of changes to the subject data
The Subject class includes a list of pointers to observers. This list is updated by the above member functions, as seen in Listing 3.
Listing 3 List Modification Using the Subject Member Functions
void Subject::Attach(Observer* o) { observers.insert (_observers.end(), o); } void Subject::Detach(Observer* o) { observers.remove(o); }
Listings 2 and 3 illustrate the base class. We use a derived class for our implementation in a class called OperationList, as shown in Listing 4.
Listing 4 Implementation Subject Class
class OperationList : public Subject { public: OperationList (); void UpdateOperations(const char*); char* getOperationList(); private: char operationList[ARRAY_SIZE]; };
OperationList provides the operation data required to keep track of the database backup process. There is one instance of OperationList for every operation, the name of which is recorded in the private data member char operationList[25]. The array contains 25 elements to allow sufficient text for operations such as DB Backup. The updates occur in the member function UpdateOperations(), as seen in Listing 5. You'll see the purpose of the Notify() method shortly.
Listing 5 Updating the Operation Status
void OperationList::UpdateOperations(char* updatedOp) { memcpy(operationList, updatedOp, strlen(updatedOp)); Notify(); }
Let's take a look at the observers now to see how it all hangs together.