Product Home Class IndexDownloadLicense

Subjects & Observers

Objects that are observers can watch other objects that are subjects. A subject can notify its observers that some event (or update) has occured. Observers are also notified whenever a subject is deleted.

Any class can be a subject by mixing-in the CK_Subject class. Likewise, any class can be an observer by mixing-in the CK_Observer class. It is possible to mixin both CK_Subject and CK_Observer if a class wishes to be both a subject and observer.

Here are some examples of classes that mixin the Chilkat subject and observer classes:

// There are no methods to override when mixing-in CK_Subject.
// To become a subject, simply derive from CK_Subject.
class ClassA : public CK_Subject
    {
    public:
	ClassA(void);
	~ClassA(void);

    };

// A class that mixes-in CK_Observer can override the subjectUpdate
// and subjectDeleted member functions.  
class ClassB : public CK_Observer
    {
    public:
	ClassB(void);
	~ClassB(void);

	// These are called when the subject is updated or deleted.
	void subjectUpdate(int subjectKey);
	void subjectDeleted(int subjectKey);
    };

// A class can be both a subject and an observer.
class ClassC : public CK_Subject, public CK_Observer
    {
    public:
	ClassB(void);
	~ClassB(void);

	void subjectUpdate(int subjectKey);
	void subjectDeleted(int subjectKey);

    };

At any time, a subject can notify it's observers of an update. This is done by calling CK_Subject's notifyObservers() method. (The programmer defines what an 'update' is for a given subject.) All objects observing the subject will have their subjectUpdate() member function called.

When a subject is deleted, all objects observing the subject will have their subjectDeleted() member function called.

Subject/Observer used within the library:

The library actually uses the subject and observer classes in several places internally. Interface components that have bitmaps, such as a CK_Label, will observe its bitmap if it is an animation. When an animation switches to the next frame, it notifies its observers of the update. All components displaying that animation will mark themselves as dirty and the Chilkat engine will redraw those components.