The intent behind the Observer Design Pattern is to define a dependecy between objects so that when main object changes its state, all the dependent objects are notified. Its upto the dependent objects to update themselves or ignore the notification.
Design time consideration
- In the main object, AKA Subject, create a Event. Also add create a signature to the event.
- Create class with Event Handler method for the event of the Subject.
- Inherit the Subclasses for different behavior. Redefine the event handler method for which any behavior is required.
- Register the event handler using the statement
SET EVENT HANDLER ... FOR O_SUBJECT
.
UML
Lets see the UML for the example.
We have a Subject class as
MAINPROCESS
. This class has the event as STATE_CHANGED
. We would trigger the event whenever there is any change in the state of the object. Thus, we raise the event when we set the new status of the object – attribute CURRENT_STATE
using the method SET_STATE( )
.
We have an abstract super class
MYFUNCTION
. We created event handler method ON_STATE_CHANGED
for the event STATE_CHANGED
of class MAINPROCESS
. We inherite two classes MYALV
and MYDB
from it. We redefine the methods to refresh their status.Code Lines
Here is the Code lines.
Explanation
When we call method
SET_STATUS
of the object LO_PROCESS
, it raises the event STATE_CHANGED
. This would be caught in the event handler ON_STATE_CHANGED
. This is possible with the statement, SET HANDLER lo_alv->on_state_changed FOR lo_process
.Output
The test program generate this output:
Don’t miss to read, The Case Study: Observer Design Pattern Usage to know more about how observer can be implemented in real-world.
No comments:
Post a Comment