abap object-oriented–使用事件
2018-07-12 本文已影响1人
46b61a5f089d
这一节我们将参照一个例子,介绍事件(event)的使用方法。
1.定义event
2.Set handler
3.Raise event
REPORT zbobo_events_5.
*---------------------------------------------------------------------*
* CLASS lcl_dog DEFINITION
*---------------------------------------------------------------------*
CLASS lcl_dog DEFINITION.
PUBLIC SECTION.
* Declare events
EVENTS:
dog_is_hungry
EXPORTING value(ex_time_since_last_meal) TYPE i.
METHODS:
constructor
IMPORTING im_name TYPE string,
set_time_since_last_meal
IMPORTING im_time TYPE i,
on_dog_is_hungry FOR EVENT dog_is_hungry OF lcl_dog
IMPORTING ex_time_since_last_meal.
ENDCLASS.
*---------------------------------------------------------------------*
* CLASS lcl_dog IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_dog IMPLEMENTATION.
METHOD constructor.
WRITE: / 'I am a dog and my name is', im_name.
ENDMETHOD.
METHOD set_time_since_last_meal.
IF im_time < 4.
SKIP 1.
WRITE: / 'You fool, I am not hungry yet'.
ELSE.
* Subsrcribe for event:
* set handler <Event handler method>
* FOR <ref_sender>!FOR ALL INSTANCES [ACTIVATION <var>]
SET HANDLER on_dog_is_hungry FOR ALL INSTANCES ACTIVATION 'X'.
* Raise event
RAISE EVENT dog_is_hungry
EXPORTING ex_time_since_last_meal = im_time.
ENDIF.
ENDMETHOD.
METHOD on_dog_is_hungry.
* Event method, called when the event dog_is_hungry is raised
SKIP 1.
WRITE: / 'You son of a bitch. I have not eaten for more than',
ex_time_since_last_meal, ' hours'.
WRITE: / 'Give me something to eat NOW!'.
ENDMETHOD.
ENDCLASS.
*---------------------------------------------------------------------*
* R E P O R T
*---------------------------------------------------------------------*
DATA: o_dog1 TYPE REF TO lcl_dog.
START-OF-SELECTION.
CREATE OBJECT o_dog1 EXPORTING im_name = 'Beefeater'.
CALL METHOD o_dog1->set_time_since_last_meal
EXPORTING im_time = 2.
* This method call will raise the event dog_is_hungy
* because time > 3
CALL METHOD o_dog1->set_time_since_last_meal
EXPORTING im_time = 5.