Reactor or Dispatcher pattern.

What is the reactor design pattern?

As the name suggests, it reacts to the client request. And dispatch the client's request to the right service. In more technical words, it demultiplex different requests to different services.

It is one of the many ways to implement event-driven architecture. The reactor design pattern teaches us how to handle multiple clients synchronously. Different clients can ask for different services from the server — the reactor pattern decuple request handling and despatching to a particular service.

The reactor maintains a lookup table, which is a kind of map which holds pointers to concrete event implementations. Though which we can call hooked methods when event occurs.

The reactor pattern cannot scaleup much, because it does serialization at the demultiplexing layer.

We can create one reactor or dispatcher for multiple events, or we can create multiple reactors, one per event. In case of multiple reactors, each reactor has its synchronous demultiplexer, but multiple synchronous demultiplexer runs parallelly.

It decuple the demultiplexer logic. Application developers need not worry about how events dispatch. They should keep their focus on business logic, and pass a hook method to reactor. The reactor invokes their hook methods when the event occurs.

As it become modular, we can write a portable code by implementing two Reactor concrete implementations. First, select()
and poll() for Unix platform. Second, WaitForMultipleObjects() for Windows Platform.


Drawbacks -

If the dispatcher is performing long-running events at handler side, it blocks the rest of the execution due to synchronous call. Though we can solve it via Active object pattern or half-sync and half async pattern, so make sure that it used for short execution events.

Related patterns -

Observer or publish-subscriber pattern, as they all inform hook methods when event is occurs.

Example - 

Please follow the sequence diagram, class diagram, and code for more understanding.
Sequence diagram -


Reactor pattern sequence diagram
Please click on the image to see the zoom view.

class diagram -

code -


Thanks for reading it. To learn more about design patterns and basic design principles, please see my web page.

Comments

Popular posts from this blog

Non-virtual interface idiom (NVI)

Factory method design pattern for beginners.

Architectural patterns => Mud to structure => layers.