Java Design Pattern: Mediator

Mediator design pattern is used to collaborate a set of colleagues. Those colleagues do not communicate with each other directly, but through the mediator.

In the example below, Colleague A want to talk, and Colleague B wants to fight. When they do some action(i.e., doSomething()), they invoke mediator to do that.

Mediator Class Diagram


Mediator Java Code

package designpatterns.mediator;
interface IMediator {
	public void fight();
	public void talk();
	public void registerA(ColleagueA a);
	public void registerB(ColleagueB a);
//concrete mediator
class ConcreteMediator implements IMediator{
	ColleagueA talk;
	ColleagueB fight;
	public void registerA(ColleagueA a){
		talk = a;
	public void registerB(ColleagueB b){
		fight = b;
	public void fight(){
		System.out.println("Mediator is fighting");
		//let the fight colleague do some stuff
	public void talk(){
		System.out.println("Mediator is talking");
		//let the talk colleague do some stuff
abstract class Colleague {
	IMediator mediator;
	public abstract void doSomething();
//concrete colleague
class ColleagueA extends Colleague {
	public ColleagueA(IMediator mediator) {
		this.mediator = mediator;
	public void doSomething() {;
//concrete colleague
class ColleagueB extends Colleague {
	public ColleagueB(IMediator mediator) {
		this.mediator = mediator;
	public void doSomething() {
public class MediatorTest {
	public static void main(String[] args) {
		IMediator mediator = new ConcreteMediator();
		ColleagueA talkColleague = new ColleagueA(mediator);
		ColleagueB fightColleague = new ColleagueB(mediator);

Among other behavioral pattern, Observer is the most similar pattern with Mediator. You can read Observer pattern to compare the difference.

Category >> Design Patterns Stories  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. javalearner on 2013-10-29

    why I think some of these patterns are almost the same .

  2. Nikolay Pasko on 2014-6-23

    You have an error in CollegueA code:
    this.mediator.registerA(this) should be called in constructor, not in doSomething() method.

Leave a comment