天天看點

ABAP實作設計模式裡的觀察者-釋出者模式

This is an interview question from Wechat development team. The candidates are required to answer with JavaScript. Nevertheless I think it is also beneficial for an ABAPer if we master the design pattern contained in this question –Publish and Subscribe pattern.

The requirement

(1) The chain operations could be performed on instance of class ZCL_PERSON.

For example, the red line 10 in ABAP code should generate the following output highlighted in red, and blue and green color accordingly.

(2) The “sleep_first” operation has the highest priority, see ABAP line 14 and its output for reference.

ABAP實作設計模式裡的觀察者-釋出者模式

Some keypoints to finish this question

(1) the operation call must support chain invoke style, which means each call must return current instance as returning parameter.

(2) In order to support the prioritization of Sleep first operation, during each operation call, the activity must not be executed immediately, or else the Sleep first operation will never have chance to be shifted to call before others. Instead, the detail information of each operation should be subscribed into a task queue, so that when a new element is inserted into that queue, we can have flexibility to adapt the order of each element in the queue, that is, if the Sleep first call is enqueued, it must always be positioned in the queue header.

The signature and implementation of subscribe method:

ABAP實作設計模式裡的觀察者-釋出者模式

When eat or sleep is called, simply log it via subscribe method and return current instance for chain invoke.

ABAP實作設計模式裡的觀察者-釋出者模式

The declaration of the series of calls ends up with method done, which calls private publish method, which loops all elements in the task queue and deal with each one by one.

ABAP實作設計模式裡的觀察者-釋出者模式

The do_task has a CASE-WHEN structure to dispatch the call to dedicated handler method according to operation type:

ABAP實作設計模式裡的觀察者-釋出者模式

The complete source code of ZCL_PERSON.

ABAP實作設計模式裡的觀察者-釋出者模式
ABAP實作設計模式裡的觀察者-釋出者模式
ABAP實作設計模式裡的觀察者-釋出者模式
ABAP實作設計模式裡的觀察者-釋出者模式

繼續閱讀