Event Model

Observer Design Pattern in Drools

Drools implements the observer pattern to allow users to listen and execute code when certain events happen; currently these events are:

  • After an object is asserted, modified or retracted.
  • After each condition check
  • After an Activation creation and cancellation
  • After a consequence is executed.

A list is used for the collection of listeners which allows the same listener to be added more than once, however removeEventListener removes all instances of the listener.

WorkingMemoryEventListener itself is an interface:


DefaultWorkingMemoryEventListener is created implementing the interface with empty methods; custom event listeners can then be created extending this class and overriding the methods for the events they wish to listen to.

WorkingMemoryEventSupport is used to facilitate the firing of events within Drools it provides methods to fire all the listeners for a given event:

The execution of each listener is done via simple iteration of the List of listeners calling the appropriate method. The following example shows what happens when an object is asserted:

ObjectAssertedEvent event = new ObjectAssertedEvent( this.workingMemory, handle, object );

for ( int i = 0, size = this.listeners.size( ); i < size; i++ )
{
    ((WorkingMemoryEventListener) this.listeners.get( i )).objectAsserted( event );
}

To allow users to use event listeners the WorkingMemory interface specifies three methods:

  • void addEventListener(WorkingMemoryEventListener listener)
  • void removeEventListener(WorkingMemoryEventListener listener)
  • List getListeners()

The getListeners exposes the underlying List, in the case of WorkingMemoryImpl, as an unmodifiable List. To add an event listener, in this case the DebugWorkingMemoryEventListener:

workingMemory.addEventListener( new DebugWorkingMemoryEventListene() );

Labels

 
(None)