This implementation supports multiple subjects for each observer. The subject passed to the Update operation lets the observer determine which subject changed when it observes more than one.
Similarly, an abstract class defines the Subject interface:
for (i.First(); !i.IsDone(); i.Next()) { i.CurrentItem()->Update(this); } }
ClockTimer is a concrete subject for storing and maintaining the time of day. It notifies its observers every second. ClockTimer provides the interface for retrieving individual time units such as the hour, minute, and second.
class ClockTimer : public Subject { public: ClockTimer();
virtual int GetHour(); virtual int GetMinute(); virtual int GetSecond();
void Tick(); };
The Tick operation gets called by an internal timer at regular intervals to provide an accurate time base. Tick updates the ClockTimer\'s internal state and calls Notify to inform observers of the change:
Now we can define a class DigitalClock that displays the time. It inherits its graphical functionality from a Widget class provided by a user interface toolkit. The Observer interface is mixed into the DigitalClock interface by inheriting from Observer.
class DigitalClock: public Widget, public Observer { public: DigitalClock(ClockTimer*); virtual ~DigitalClock();
void DigitalClock::Draw () { // get the new values from the subject
int hour = _subject->GetHour(); int minute = _subject->GetMinute(); // etc.
// draw the digital clock }
An AnalogClock class can be defined in the same way.
class AnalogClock : public Widget, public Observer { public: AnalogClock(ClockTimer*); virtual void Update(Subject*); virtual void Draw(); // ... };
The following code creates an AnalogClock and a DigitalClock that always show the same time:
ClockTimer* timer = new ClockTimer; AnalogClock* analogClock = new AnalogClock(timer); DigitalClock* digitalClock = new DigitalClock(timer);
Whenever the timer ticks, the two clocks will be updated and will redisplay themselves appropriately.
Kilde: Design Patterns CD
Synes godt om
Ny brugerNybegynder
Din løsning...
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.