State Design Pattern: Reminder

来源:互联网 发布:java 获取跳转后的url 编辑:程序博客网 时间:2024/06/05 05:59
Purpose
Make the state chart topology more flexible by inventing an event and posting it to self.

Problem
Often in state modeling, loosely related functions of a system are strongly coupled by a common event. Consider, for example, periodic data acquisition, in which a sensor producing the data needs to be polled at a predetermined rate. Assume that a periodic TIMEOUT event is dispatched to the system at the desired rate to provide the stimulus for polling the sensor. Because the system has only one external event (the TIMEOUT event), it seems that this event needs to trigger both the polling of the sensor and the processing of the data. A straightforward but suboptimal solution is to organize the state machine into two distinct orthogonal regions (for polling and processing). However, orthogonal regions increase the cost of dispatching events and require complex synchronization between the regions (polling and processing are not quite orthogonal).

Solution
A simpler and more efficient solution is to invent a stimulus (DATA_READY) and to propagate it to self as a reminder that the data is ready for processing as below Figure. This new stimulus provides a way to decouple polling from processing without using orthogonal regions. Moreover, you can use state nesting to arrange these two functions in a hierarchical relation to take advantage of behavioral inheritance. In the most basic arrangement, the processing state can be a substate of polling and can simply inherit the polling behavior so that polling occurs in the background to processing. However, the processing state might also choose to override polling. For instance, to prevent flooding the CPU with sensor data, processing might inhibit polling occasionally. The statechart in the below Figure illustrates this option. The busy substate of processing overrides the TIMEOUT event and thus prevents this event from being handled in the higher level polling superstate.

Further flexibility of this solution entails fine control over the generation of the invented DATA_READY event, which does not have to be posted at every occurrence of the original TIMEOUT event. For example, to improve performance, the polling state could buffer the raw sensor data and generate the DATA_READY event only when the buffer fills up, Figure illustrates this option with the if (...) condition, which precedes the post(DATA_READY) action in the polling state.

_bm12


Note:
1) Developers could utilize State Machine Engine API SmePostEvent to post event to myself state.
2) If there are 2 event handlers for an event in substate and superstate respectively. The substate's event handler will override the superstate's event handler.
Figure: Reminder State Design Pattern
原创粉丝点击