Mediator pattern
From Free net encyclopedia
←Older revision | Newer revision→
The mediator pattern is a software design pattern that provides a unified interface to a set of interfaces in a subsystem.
Usually a program is made up of a (sometimes large) number of classes. So the logic and computation is distributed among these classes. However, as more classes are developed in a program, especially during maintenance and/or refactoring, the problem of communication between these classes may become more complex.
This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes.
The Mediator pattern addresses this problem by promoting looser coupling between these classes by being the only class that has detailed knowledge of the methods of other classes. Classes send messages to the mediator when needed and the Mediator passes them on to any other classes that need to be informed.
Examples
Java
The following Java program illustrates the Mediator pattern. It outputs:
Sending message from kim to toni: Hello world. Received message by toni: Hello world. Sending message from rene to kim: Greetings! Received message by kim: Greetings!
import java.util.*; interface Mediator { public void send(String id, String message); } class ConcreteMediator implements Mediator { private HashMap<String, Colleague> colleagues = new HashMap<String, Colleague>(); public void registerColleague(Colleague c) { c.registerMediator(this); colleagues.put(c.getId(), c); } public void send(String id, String message) { colleagues.get(id).receive(message); } } class Colleague { private Mediator mediator; private String id; public Colleague(String id) { this.id = id; } public void registerMediator(Mediator mediator) { this.mediator = mediator; } public String getId() { return id; } public void send(String id, String message) { System.out.println("Sending message from "+this.id+" to "+id+": "+message); mediator.send(id, message); // Dispatch the actual communication to the mediator!!! } public void receive(String message) { System.out.println("Received message by "+id+": "+message); } } class MediatorExample { public static void main(String[] args) { Colleague rene = new Colleague("rene"); Colleague toni = new Colleague("toni"); Colleague kim = new Colleague("kim"); ConcreteMediator m = new ConcreteMediator(); m.registerColleague(rene); m.registerColleague(toni); m.registerColleague(kim); kim.send("toni", "Hello world."); rene.send("kim", "Greetings!"); } }