Java mediator design pattern

Dictionary meaning of mediator: a person who attempts to make people involved in a conflict come to an agreement.

Java mediator design pattern comes under behavioural design patterns. Mediator design pattern is used to provide the loose coupling or to reduce the interaction complexity between multiple objects.

Let’s discuss mediator design pattern with below example. We are considering group chat application. A user can send and receive the messages. If a user send a message, it should be received by all other members in the group.

Example

ChatMediator.java

package com.w3spoint;
 
public class ChatMediator {
	public static void displayMessage(String msg, User user){
		System.out.println("User: " + user.getName() + ", Message: " + msg);
	}
}

User.java

package com.w3spoint;
 
public class User {
   private String name;
 
   public String getName() {
      return name;
   }
 
   public void setName(String name) {
      this.name = name;
   }
 
   public User(String name){
      this.name  = name;
   }
 
   public void sendMessage(String message){
      ChatMediator.displayMessage(message,this);
   }
}

Tennis.java

package com.w3spoint;
 
public class MediatorPatternTest {
   public static void main(String args[]){
      User bharat = new User("Bharat");
      User sahdev = new User("Sahdev");
      User richi = new User("Richi");
 
      bharat.sendMessage("Hello Richi");
      richi.sendMessage("Hello Bharat");
      sahdev.sendMessage("Hi all");
   }
}

Output

User: Bharat, Message: Hello Richi
User: Richi, Message: Hello Bharat
User: Sahdev, Message: Hi all
Content Protection by DMCA.com
Please Share