C++ Mediator Pattern for Object Interaction
- Object Interactions
- Object Interaction Scenario in IT Management
- Example of a Mediator
- Mediator Base Class
- Mediator Subclass
- Widget Class
- Two Widget Subclasses
- LspDirector Implementation
- Widget Class Implementation
- PathWidget Class Implementation
- Putting It All Together
- Additional Reading
Perhaps the greatest promise of object-oriented development was the move away from monolithic software (software with a multitude of highly coupled components). The problem with monolithic code is that the large number of cross connections between components makes it very hard to change or maintain. I reckon we’ve all fallen foul of such software!
Object-oriented languages and design approaches promised to change all that! The surprising thing is that it’s just as easy to create monolithic C++ or Java applications. Unfortunately, long experience teaches that it’s all too easy to produce bad software! As a great chess player once remarked: "The mistakes are all there waiting to be made." The corollary is that all the good moves are also there waiting to be made. So, with a little thought and planning, we all can produce excellent software.
In software, the area in which individual objects interact seems to present much difficulty. If we get the interaction patterns wrong, the possibility of successful reuse and componentization is also reduced. The mediator design pattern provides an elegant solution to the problem of object interaction. Objects that need to communicate with each other use a mediator object for all interactions. The mediator then handles the communication with target objects – in effect the mediator becomes an intermediary. Interdependent objects know only about the mediator—they have little or no knowledge about the other objects. In short, the mediator facilitates decoupling.
A sneak preview of the completed C++ code is illustrated in Listing 1.
Listing 1 Mediator for Handling a Number of Widgets
LspDirector* anExampleMediator = new LspDirector(555); anExampleMediator->CreateWidgets(); anExampleMediator->ChangePath("R5R6"); anExampleMediator->ChangeQoSDetails("Expedited Forwarding");
In Listing 1, I create a mediator object that acts as the intermediary between a group of interdependent objects. The latter are sometimes called widgets to convey the fact that they are components in a broader structure. I guess an up-to-the-minute description would use the term components instead, but you get the idea! I create the widgets with an initial configuration (at construction time, not shown in Listing 1). I then change the configuration of the widgets and observe how it is reflected in the mediator.
Let’s take a very brief detour to see a simple application for the mediator.