The fire alarm is represented by an object of class Alarm
, a subclass of Subject
. The fire department, center owner, and shops are represented by instances of class Stakeholder
which in turn is a subclass of Observer
.
class Alarm(id: var String): Subject
whatWentWrong:
" - smoke detected\n".print
alert:
notifyObservers
class Stakeholder(id: var String): Observer
ObservedSubject::< Alarm
notify::
theSubject.whatWentWrong
fireAlarm.subscribe(this(StakeHolder))
fireAlarm: obj Alarm("fireAlarm")
fireDepartment: obj Stakeholder("FireDepartment")
centerOwner: obj Stakeholder("CenterOwner")
shopA: obj StakeHolder("ShopA")
shopB: obj StakeHolder("ShopB")
shopC: obj StakeHolder("ShopC")
- Class
Alarm
has anid
identifying the alarm. - It has a method
whatWentWrong
that may supply information to anObserver
when notified. - It has a method
alert
that is invoked by a fire censor in case a fire is detected. - Class
StakeHolder
is a subclass ofObserver
. - It has an
id
identifying theObserver
. - It makes further binding of
notify
, which invokestheSubject.whatWentWrong
. - It makes a further binding of class
ObservedSubject
toAlarm
. - Note that
theSubject
(the parameter ofnotify
) is of typeObservedSubject
, and since it is bound toAlarm
, the methodwhatWentWrong
may be invoked. - It invokes
fireAlarm.subscribe(this(StakeHolder))
and thereby subscribe to events fromfireAlarm
. - The object
fireAlarm
is declared as an instance of classAlarm
. - The
Observer
objectsFireDepartment
, etc. are declared as instances of classStakeholder
.
The next diagram illustrates the situation where the subject fireAlarm
has references to all the Observers
, and the argument, theSubject
of invocations of notify
on an Observer
refers to the fireAlarm
object.
When the Stakeholder
objects are generated, they all subscribe to events from the fireAlarm
. At some point in time an external sensor may detect a possible fire and invoke fireAlarm.alert
, which then invokes notifyObservers
, which in turn invoke notify
on all Stakeholder
objects. This is illustrated by the following OSD.
The invocations of notify
all invoke whatWentWong
on the FireAlarm
, but this is not shown in the above diagram.
In the above example, the FireAlarm
is the only subject being observed. It is of course possible to add more FireAlarm
objects at different places in the shopping center or at other locations. The FireDepartment
will then observe all the FireAlarms
whereas the shops and owner of a given shopping center only observe the alarm in that center.