Skip to content
-
Mediator Design Pattern in Java
Last Updated :
06 Dec, 2023
The mediator design pattern defines an object that encapsulates how a set of objects interact.
The Mediator is a behavioral pattern (like the Observer or the Visitor pattern) because it can change the program's running behavior.
We are used to see programs that are made up of a large number of classes. However, as more classes are added to a program, the problem of communication between these classes may become more complex.
Because of this, the maintenance becomes a big problem that we need to solve in this way or another.
Like in many other Design Patterns, The mediator pattern comes to solve the problem. It makes the communication between objects encapsulated with a mediator object.
Objects don't communicate directly with each other, but instead, they communicate through the mediator.
Mediator pattern implementation in Java
This program illustrates an auction. The Auction Mediator is responsible for adding the buyers, and after each buyer bid a certain amount for the item, the mediator know who won the auction.
Class diagram:

Java
// Java code to illustrate Mediator Pattern
// All public class codes should be put in
// different files.
public interface Mediator {
// The mediator interface
public void addBuyer(Buyer buyer);
public void findHighestBidder();
}
public class AuctionMediator implements Mediator {
// this class implements the interface and holds
// all the buyers in a Array list.
// We can add buyers and find the highest bidder
private ArrayList buyers;
public AuctionMediator()
{
buyers = new ArrayList<>();
}
@Override
public void addBuyer(Buyer buyer)
{
buyers.add(buyer);
System.out.println(buyer.name + " was added to" +
"the buyers list.");
}
@Override
public void findHighestBidder()
{
int maxBid = 0;
Buyer winner = null;
for (Buyer b : buyers) {
if (b.price > maxBid) {
maxBid = b.price;
winner = b;
}
}
System.out.println("The auction winner is " + winner.name +
". He paid " + winner.price + "$ for the item.");
}
}
public abstract class Buyer {
// this class holds the buyer
protected Mediator mediator;
protected String name;
protected int price;
public Buyer(Mediator med, String name)
{
this.mediator = med;
this.name = name;
}
public abstract void bid(int price);
public abstract void cancelTheBid();
}
public class AuctionBuyer extends Buyer {
// implementation of the bidding process
// There is an option to bid and an option to
// cancel the bidding
public AuctionBuyer(Mediator mediator,
String name)
{
super(mediator, name);
}
@Override
public void bid(int price)
{
this.price = price;
}
@Override
public void cancelTheBid()
{
this.price = -1;
}
}
public class Main {
/* This program illustrate an auction. The AuctionMediator
is responsible for adding the buyers, and after each
buyer bid a certain amount for the item, the mediator
know who won the auction. */
public static void main(String[] args)
{
AuctionMediator med = new AuctionMediator();
Buyer b1 = new AuctionBuyer(med, "Tal Baum");
Buyer b2 = new AuctionBuyer(med, "Elad Shamailov");
Buyer b3 = new AuctionBuyer(med, "John Smith");
// Create and add buyers
med.addBuyer(b1);
med.addBuyer(b2);
med.addBuyer(b3);
System.out.println("Welcome to the auction. Tonight " +
"we are selling a vacation to Vegas." +
" please Bid your offers.");
System.out.println("--------------------------------" +
"---------------");
System.out.println("Waiting for the buyer's offers...");
// Making bids
b1.bid(1800);
b2.bid(2000);
b3.bid(780);
System.out.println("---------------------------------" +
"--------------");
med.findHighestBidder();
b2.cancelTheBid();
System.out.print(b2.name + " Has canceled his bid!, " +
"in that case ");
med.findHighestBidder();
}
}
Output:
Tal Baum was added to the buyers list.
Elad Shamailov was added to the buyers list.
John Smith was added to the buyers list.
Welcome to the auction. Tonight we are
selling a vacation to Vegas. please Bid your offers.
-----------------------------------------------
Waiting for the buyer's offers...
-----------------------------------------------
The auction winner is Elad Shamailov.
He paid 2000$ for the item.
Elad Shamailov Has canceled his bid!, In that
case The auction winner is Tal Baum.
He paid 1800$ for the item.
Advantages:
- Simplicity
- You can replace one object in the structure with a different one without affecting the classes and the interfaces.
Disadvantages:
- The Mediator often needs to be very intimate with all the different classes, And it makes it really complex.
- Can make it difficult to maintain.
Author : http://designpattern.co.il/
Similar Reads
Java Design Patterns Tutorial Design patterns in Java refer to structured approaches involving objects and classes that aim to solve recurring design issues within specific contexts. These patterns offer reusable, general solutions to common problems encountered in software development, representing established best practices. B
8 min read
Creational Software Design Patterns in Java
Factory Method Design Pattern in Java It is a creational design pattern that talks about the creation of an object. The factory design pattern says to define an interface ( A java interface or an abstract class) for creating the object and let the subclasses decide which class to instantiate. Table of ContentWhat is the Factory Method D
6 min read
Builder Method Design Pattern in Java Method Chaining: In java, Method Chaining is used to invoke multiple methods on the same object which occurs as a single statement. Method-chaining is implemented by a series of methods that return the this reference for a class instance.Implementation: As return values of methods in a chain is this
5 min read
Builder, Fluent Builder, and Faceted Builder Method Design Pattern in Java Builder Pattern is defined as a creational design pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing us to create different variations of an object with the same construction code. This pattern is particularly
8 min read
Singleton Design Pattern in Java Singleton Design Pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to it. This pattern is particularly useful when exactly one object is needed to coordinate actions across the system. Important Topics for Singleton Method in Java
5 min read
Structural Software Design Patterns in Java
Composite Design Pattern in Java The Composite Design Pattern is a structural design pattern that lets you compose objects into tree-like structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. In other words, whether dealing with a single object or a grou
8 min read
Decorator Method Design Pattern in Java A structural design pattern called the Decorator Design Pattern enables the dynamic addition of functionality to specific objects without changing the behavior of other objects in the same class. To wrap concrete components, a collection of decorator classes must be created. Decorator Method Design
10 min read
Design Patterns in Java - Iterator Pattern A design pattern is proved solution for solving the specific problem/task. We need to keep in mind that design patterns are programming language independent for solving the common object-oriented design problems. In Other Words, a design pattern represents an idea, not a particular implementation. U
5 min read
`;
$(commentSectionTemplate).insertBefore(".article--recommended");
}
loadComments();
});
});
function loadComments() {
if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}