DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Creating a Deep vs. Shallow Copy of an Object in Java
  • Java String: A Complete Guide With Examples

Trending

  • Transforming Software Development With Low-Code and No-Code Integration
  • From Backlog Manager to Product Manager [Video]
  • Javac and Java Katas, Part 1: Class Path
  • OpenID Connect Flows: From Implicit to Authorization Code With PKCE and BFF
  1. DZone
  2. Coding
  3. Languages
  4. Mediator Pattern Tutorial with Java Examples

Mediator Pattern Tutorial with Java Examples

Learn the Mediator Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
Apr. 26, 10 · Tutorial
Like (3)
Save
Tweet
Share
112.3K Views

Join the DZone community and get the full member experience.

Join For Free

Today's pattern is the Mediator pattern, used to handle complex communications between related objects, helping with decoupling of those objects.

Mediator in the Real World 

An airport control tower is an excellent example of the mediator pattern. The tower looks after who can take off and land - all communications are done from the airplane to control tower, rather than having plane-to-plane communication. This idea of a central controller is one of the key aspects to the mediator pattern.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Mediator Pattern

The Mediator pattern is known as abehavioural pattern, as it's used to manage algorithms, relationships and responsibilities between objects.. Thedefinition of Mediator as provided in the original Gang of Four book on DesignPatterns states: 

Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other.  Allows for the actions of each object set to vary independently of one another.  

The following diagram shows how the mediator pattern is modelled.

 

The Mediator defines the interface for communication between Colleague objects. The ConcreteMediator implements the Mediator interface and coordinates communication between Colleague objects. It is aware of all the Colleagues and their purpose with regards to inter communication.The ConcreteColleague communicates with other colleagues through the mediator.

Without this pattern, all of the Colleagues would know about each other, leading to high coupling. By having all colleagues communicate through one central point we have a decoupled system while maintaining control on the object's interactions.

When Would I Use This Pattern?

The mediator is a good choice of pattern when the communication between objects is complicated, but well defined. When there are too many relationships between the objects in your code, it's time to think of having such a central point of control.

An observer based variation of the mediator pattern is used in Java Message Service (JMS) implementations, which allows applications to subscribe and publish data to other applications. This is a common combination of patterns that makes sense.

So How Does It Work In Java?

Here we'll use the Mediator pattern in the context of a chatroom application. First we'll define an interface for our mediator

//Mediator interface
public interface Mediator {
  public void send(String message, Colleague colleague);
}

While we described the Colleague as an interface above, it's more useful to use an abstract class in this case:

//Colleage interface
public abstract Colleague{
  private Mediator mediator;
  public Colleague(Mediator m) {
    mediator = m;
  }
  //send a message via the mediator
  public void send(String message) {
    mediator.send(message, this);
  }
  //get access to the mediator
  public Mediator getMediator() {return mediator;}
  public abstract void receive(String message);
}

Now let's create our concrete mediator implementation

public class ApplicationMediator implements Mediator {
  private ArrayList<Colleague> colleagues;
  public ApplicationMediator() {
    colleagues = new ArrayList<Colleague>();
  }
  public void addColleague(Colleague colleague) {
    colleagues.add(colleague);
  }
  public void send(String message, Colleague originator) {
    //let all other screens know that this screen has changed
    for(Colleague colleague: colleagues) {
      //don't tell ourselves
      if(colleague != originator) {
        colleage.receive(message);
      }
    }
  }
}

Finally we'll create one concrete colleage. 

public class ConcreteColleague extends Colleague {
  public void receive(String message) {
    System.out.println("Colleague Received: " + message);
  }
}

If we assume that we could have many different colleagues that react differently when a message is received, this pattern fits in well. For example, we could have a mobileColleague that needs to display the message differently to the desktop colleague.

public class MobileColleague extends Colleague {
  public void receive(String message) {
    System.out.println("Mobile Received: " + message);
  }
}

 

Here's a client that drives the entire application: 

public class Client {
  public static void main(String[] args) {
    ApplicationMediator mediator = new ApplicationMediator();
    ConcreteColleague desktop = new ConcreteColleague(mediator);
    ConcreteColleague mobile = new MobileColleague(mediator);
    mediator.addColleague(desktop);
    mediator.addColleague(mobile);
    desktop.send("Hello World");
    mobile.send("Hello");
  }
}

Watch Out for the Downsides

While this pattern aims to reduce complexity, without proper design, the Mediator object itself can become very complicated itself.The Observer pattern could help here, with the colleague objects dealing with the events from the mediator, rather than having the mediator look after all orchestration.

Next Up

Later on this week we'll be taking a look at the Interpreter pattern.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern


Mediator (software) Mediator pattern Java (programming language) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Creating a Deep vs. Shallow Copy of an Object in Java
  • Java String: A Complete Guide With Examples

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: