ABAP Object 之 Event

OO特点是什么,封装,多态,继承. 在当下流行的编程语言中, 支持面向对象成为了最大的共同点,比如JAVA, C#.等. 而对于ABAP语言, 90年代后期, SAP对ABAP/4进行了扩展以支持面向对象, 称之为ABAP Objects. 其广泛应用在如SAP EnjoySAP controls, RTTS, Workflow, WebDynpro等之中. 比如说NW7.0中ALV的OO模型,将List与Grid的实现进行封装到一个类中, 而你只需要更改一下构造参数即可分别支持List与Grid输出.

ABAP Objects 同其它支持OO的语言一样也支持封装,多态,继承. 而比较有意思的一点是其在语言级别支持定义事件,使得在ABAP中非常容易实现订阅—发布机制. 这跟在JAVA中支持观察者模式差不多, 都是在当一个对象的状态发生改变时,可以通知多个依赖于它的对象, 而发布者对于有哪些订阅者并不感兴趣, 从而将两者之间的关系松耦合.事件发生时, 事件的触发者并不知道有哪些对象会作出回应, 其对事件如何进行处理.

看个实例

场景: 一个产品当改变价格时,需要通知多个客户, 价钱已更改, 另外由日志类记录日志.

1. 定义事件

priceChanged

CLASS lcl_product DEFINITION.

PUBLIC SECTION.

EVENTS: pricechanged.

PRIVATE SECTION.

DATA: price TYPE i.

ENDCLASS. "lcl_product DEFINITION

2. 定义如何触发

CLASS lcl_product DEFINITION.

PUBLIC SECTION.

EVENTS: pricechanged.

METHODS:

raise_event.

PRIVATE SECTION.

DATA: price TYPE i.

ENDCLASS. "lcl_product DEFINITION

CLASS lcl_product IMPLEMENTATION.

METHOD raise_event.

WRITE: / '------------------------------------'.

WRITE: / 'Before event trrigger'.

RAISE EVENT pricechanged.

WRITE: / 'After event trrigger'.

WRITE: / '------------------------------------'.

ENDMETHOD. "raise_event

ENDCLASS. "lcl_product IMPLEMENTATION

3. 定义事件处理

*----------------------------------------------------------------

* CLASS lcl_customer

*----------------------------------------------------------------

CLASS lcl_customer DEFINITION.

PUBLIC SECTION.

METHODS:

handle_price_changed FOR EVENT pricechanged OF lcl_product

IMPORTING sender.

ENDCLASS. "lcl_customer DEFINITION

CLASS lcl_customer IMPLEMENTATION.

METHOD handle_price_changed.

WRITE: / ' Customer handle changed price'.

ENDMETHOD. "handle_price_changed

ENDCLASS. "lcl_customer IMPLEMENTATION

*----------------------------------------------------------------

* CLASS lcl_logger

*----------------------------------------------------------------

CLASS lcl_logger DEFINITION.

PUBLIC SECTION.

METHODS:

handle_price_changed FOR EVENT pricechanged OF lcl_product

IMPORTING sender.

ENDCLASS. "lcl_logger DEFINITION

CLASS lcl_logger IMPLEMENTATION.

METHOD handle_price_changed.

WRITE: / ' Logger log changed price'.

ENDMETHOD. "handle_price_changed

ENDCLASS. "lcl_logger IMPLEMENTATION

4. 注册事件处理

* Create object instances

CREATE OBJECT grf_product.

CREATE OBJECT grf_customer.

CREATE OBJECT grf_logger.

* Register event

SET HANDLER grf_customer->handle_price_changed FOR grf_product.

SET HANDLER grf_logger->handle_price_changed FOR grf_product.

* Trigger event

grf_product->raise_event( ).

很美妙的事情, 我们并不需要直接发送消息给客户,日志类,就可以让他们知道价格已更改, 从而使代码松耦合.

你可能感兴趣的:(编程,workflow,OO)