We want to design reusable components, but dependencies between the potentially reusable pieces demonstrates the “spaghetti code” phenomenon (trying to scoop a single serving results in an “all or nothing clump”).
In Unix, permission to access system resources is managed at three levels of granularity: world, group, and owner. A group is a collection of users intended to model some functional affiliation. Each user on the system can be a member of one or more groups, and each group can have zero or more users assigned to it. Next figure shows three users that are assigned to all three groups.
If we were to model this in software, we could decide to have User objects coupled to Group objects, and Group objects coupled to User objects. Then when changes occur, both classes and all their instances would be affected.
An alternate approach would be to introduce “an additional level of indirection” - take the mapping of users to groups and groups to users, and make it an abstraction unto itself. This offers several advantages: Users and Groups are decoupled from one another, many mappings can easily be maintained and manipulated simultaneously, and the mapping abstraction can be extended in the future by defining derived classes.
Partitioning a system into many objects generally enhances reusability, but proliferating interconnections between those objects tend to reduce it again. The mediator object: encapsulates all interconnections, acts as the hub of communication, is responsible for controlling and coordinating the interactions of its clients, and promotes loose coupling by keeping objects from referring to each other explicitly.
The Mediator pattern promotes a “many-to-many relationship network” to “full object status”. Modelling the inter-relationships with an object enhances encapsulation, and allows the behavior of those inter-relationships to be modified or extended through subclassing.
An example where Mediator is useful is the design of a user and group capability in an operating system. A group can have zero or more users, and, a user can be a member of zero or more groups. The Mediator pattern provides a flexible and non-invasive way to associate and manage users and groups.
Colleagues (or peers) are not coupled to one another. Each talks to the Mediator, which in turn knows and conducts the orchestration of the others. The “many to many” mapping between colleagues that would otherwise exist, has been “promoted to full object status”. This new abstraction provides a locus of indirection where additional leverage can be hosted.
The Mediator defines an object that controls how a set of objects interact. Loose coupling between colleague objects is achieved by having colleagues communicate with the Mediator, rather than with each other. The control tower at a controlled airport demonstrates this pattern very well. The pilots of the planes approaching or departing the terminal area communicate with the tower rather than explicitly communicating with one another. The constraints on who can take off or land are enforced by the tower. It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.
Object oriented design encourages the distribution of behaviour among objects. Such distribution can result in an object structure with many connections between objects; in the worst case, every object ends up knowing about every other.
Though partitioning a system into many objects generally enhances reusability, proliferating interconnections tend to reduce it again. Lots of interconnections make it less likely that an object can work without the support of others - the system acts as though it were monolithic. Moreover it can be difficult to change the systems’ behaviour in any significant way, since behaviour is distributed among many objects. As a result, you may be forced to define many subclasses to customise the system’s behaviour.
Developers at Borland probably were aware of the above mentioned paragraphs when designing the Delphi Object Pascal language and the VCL components. Their solution to this problem is essentially: events (or method pointers). The use of events makes de-coupling of objects possible. The class TForm
is their standard mediator class which handles (wires) events from components put on the form.
They even delivered a great tool with it: the Object Inspector. Being able to delegate behaviour to another class using events, saves you, for example, from subclassing TButton
when you need a button that interacts with an TEdit
control. The mediator is the form which handles all events and takes corresponding actions, coupling all related components together with snippets of code. Great. So what’s the need for a Mediator pattern?
Delphi’s Object Inspector uses RTTI and form designers to create event handlers on forms and Delphi’s component streaming mechanism takes care of actually wiring these events at run time.
If you ever manually created event handlers you know that you have to:
FSample.OnChange := SampleChange;
In order to construct a correct event handler method it needs the event type definition. The mediator pattern relies on these event type definitions to construct and update event handlers.
Suppose we’ve created a class TComPort
which encapsulates a serial port device driver. This class defines a series of events to asynchronously inform clients of state changes: data triggers, line errors etc. A TController
class could ‘use a’ TComPort
class to transmit data through a serial port.
This TController
class would typically wire and handle the Comport
events to update it’s internal state. Here’s an abstract of the interface and implementation of TComport
and TController
without the mediator:
1: type
2: TLineEvent = procedure (Sender: TObject; Error: TLineError) of object;3: TTriggerEvent = procedure (Sender: TObject; Trigger: TTrigger) of object;4:5: TComPort = class (TObject)6: published7: property OnDataReceived: TTriggerEvent read FOnDataReceived write FOnDataReceived;8: property OnLineEvent: TLineEvent read FOnLineEvent write FOnLineEvent;9: property OnTimeOut: TNotifyEvent read FOnTimeOut write FOnTimeOut;10: property OnTransmitted: TNotifyEvent read FOnTransmitted write FOnTransmitted;11: end;
12:13: TController = class (TObject)14: private15: FComPort: TComPort;16: public17: constructor Create;
18: destructor Destroy; override;
19: property ComPort: TComPort read FComPort;20: end;
21:22: implementation
23:24: constructor TController.Create;
25: begin
26: inherited Create;
27: FComPort := TComPort.Create;28: end;
29:30: destructor TController.Destroy;
31: begin
32: FComPort.Free;33: inherited Destroy;
34: end;
Now have a look at the same abstract for classTController
with the mediator applied to this structure:
1: TController = class (TObject)2: private3: FComPort: TComPort;4: protected5: procedure ComPortDataReceived(Sender: TObject; Trigger: TTrigger);
6: procedure ComPortLineEvent(Sender: TObject; Error: TLineError);
7: procedure ComPortTimeOut(Sender: TObject);
8: procedure ComPortTransmitted(Sender: TObject);
9: procedure UnwireComPort;
10: procedure WireComPort;
11: public12: constructor Create;
13: destructor Destroy; override;
14: property ComPort: TComPort read FComPort;15: end;
16:17: implementation
18:19: constructor TController.Create;
20: begin
21: inherited Create;
22: FComPort := TComPort.Create;23: //now wire comport calling the method created by the mediator
24: WireComport;25: end;
26:27: destructor TController.Destroy;
28: begin
29: //make sure the comport is unwired again
30: UnwireComport;31: FComPort.Free;32: inherited Destroy;
33: end;
34:35: procedure TController.ComPortDataReceived(Sender: TObject; Trigger: TTrigger);
36: begin
37: end;
38:39: procedure TController.ComPortLineEvent(Sender: TObject; Error: TLineError);
40: begin
41: end;
42:43: procedure TController.ComPortTimeOut(Sender: TObject);
44: begin
45: end;
46:47: procedure TController.ComPortTransmitted(Sender: TObject);
48: begin
49: end;
50:51: procedure TController.UnwireComPort;
52: begin
53: FComPort.OnDataReceived := nil;
54: FComPort.OnLineEvent := nil;
55: FComPort.OnTimeOut := nil;
56: FComPort.OnTransmitted := nil;
57: end;
58:59: procedure TController.WireComPort;
60: begin
61: FComPort.OnDataReceived := ComPortDataReceived;62: FComPort.OnLineEvent := ComPortLineEvent;63: FComPort.OnTimeOut := ComPortTimeOut;64: FComPort.OnTransmitted := ComPortTransmitted;65: end;
In this example notice: The wiring of the comport inconstructor Create
by a call toWireComPort
. This method is optionally created by the mediator. The corresponding unwiring indestructor Destroy
by a call toUnwireComPort
. This method is optionally created by the mediator. The event handler methods which all have the correct signature (as defined in the event library), just like the Object Inspector would do.