Design Patterns - SPLessons

Mediator Pattern

Chapter 23

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Mediator Pattern

Mediator Pattern

shape Description

Mediator Pattern is used to reduce the complexity of communication between the objects and is mainly used in enterprise applications. Objects of a system that communicate with each other are known as colleagues. The communication can be done through an interface or abstract class.

shape Advantages

  • Communication can be done easily.
  • Relationship can be managed easily.

shape Conceptual
figure

shape Examples

import java.util.*;
public class Room 
{
	public static void showMessage(User user, String message)//creating a static method
{
	      System.out.println(new Date().toString() + " [" + user.getName() + "] : " + message);
	   }

}
public class Person
 {
	private String name;
	   public String getPerson()//as the return type expected is String so String datatype is used 
{
	      return name;
	   }
	   public void setPerson(String name)//as method doesnot return anything void is used 
{
	      this.name = name;
	   }

	   public User(String name)
{
	      this.name  = name;
	   }
	   public void sendMessage(String message)
{
	      ChatRoom.showMessage(this,message);
	   }
}
public class MediatorPattern 
{
	 public static void main(String[] args) 
{
	      Person robert = new User("John");//creating object for class Person
	      Person john = new User("Jackson");//creating object for class Person

	      robert.sendMessage("Hi! John!");
	      john.sendMessage("Hello! Jackson!");
	   }
}

In the above example-class room, class person is a different classes but communication can be done between them using MediatorPattern class.

shape Output

The result will be as follows.

 Tue Feb 16 16:05:46 IST 2016 [John] : Hi! Jackson!
Tue Feb 16 16:05:46 IST 2016 [Jackson] : Hello! John!

Summary

shape Key Points

  • Mediator Pattern – Mediator Pattern makes the communication process easy.
  • Mediator Pattern – Loose-coupling between the objects can be done easily.