How to implement Mediator pattern in Java?

Let’s say you want to automate posting on social media.

You want to update your twitter and blog feed automatically when you post on facebook.

Similarly if you post on any other media, the other two media should get the feed automatically updated.

Let’s represent this problem in Java.

You can have a class for each of the social media accounts.

And then you can have a reference of each media class inside all the other media classes.

Twitter will have a reference to your Facebook account and your blog.

Facebook will have a reference to your Twitter account and your blog.

Your blog will have a reference to Twitter and Facebook.

Now that looks ugly.

Every time you post on a social media , the particular media class calls post API on the other two media.

Imagine adding more social media accounts.

Your class gets overloaded with references and becomes tightly coupled.

What can you do?

Mediator pattern comes for rescue.

All your social media account has to do in mediator pattern is to delegate the feed update to the mediator. Every media account will communicate to every other account through the Mediator. The Mediator acts like an intermediate , a broker.

If there is a post on one of the social media, the mediator iterates through all the other social media accounts (registered with it) and call their APIs.

Mediator pattern acts as an intermediate for interaction between multiple objects of the same type, which have many-to-many relationships with each other.

Here is the client code:

package behavioural.mediator.pattern;

public class Client {

	public static void main(String a[]) {

		SocialMediaMediator mediator = new SocialMediaMediator();

		Facebook fb = new Facebook(mediator);
		Twitter twitter = new Twitter(mediator);
		Blog blog = new Blog(mediator);

		mediator.register(fb);
		mediator.register(twitter);
		mediator.register(blog);

		fb.post("Celebrated my birthday today with family and friends!");

		twitter.post("Finished reading the book - The Art of Negotiation. Here is my review ...(link)");

		blog.post(
				"The Writers Story : It was a lazy Sunday afternoon. The sun was hot and the writer took a walk down the street");

	}

}

I have created a SocialMediaMediator class and passed the instance to the constructor of all the social media classes : Twitter,Facebook and Blog.

All these accounts are in turn registered with the Social Media Mediator.

This way the social media accounts have a reference to the Mediator and the Mediator has a reference to the social media accounts .

And then I am calling on. post-method of each social media account to post a text on their feed.

Now, let’s see how the Mediator takes care of updating all other media feeds.

Here is the Social Media Mediator class:

package behavioural.mediator.pattern;

import java.util.ArrayList;
import java.util.List;

public class SocialMediaMediator {

	List<SocialMedia> socialMediaList = new ArrayList<SocialMedia>();

	public void register(SocialMedia media) {

		this.socialMediaList.add(media);
	}

	public void notifyMediator(SocialMedia media, String text) {

		for (SocialMedia socialMedia : this.socialMediaList) {

			if (!socialMedia.getClass().equals(media.getClass())) {

				socialMedia.postFromOtherMedia(media.getClass().getSimpleName(), text);
			}
		}

	}

}

As you can see , every time a social media class is registered , it is added to a list of social media classes.

And when the mediator is notified through notifyMediator() method , the list is iterated and each social media feed is updated through the method postFromOtherMedia().

A condition check is done to make sure a post from a particular social media is not posted again on its own feed through the mediator.

Now lets look at one of the Social Media classes:

package behavioural.mediator.pattern;

public class Facebook implements SocialMedia {

	SocialMediaMediator mediator;

	public Facebook(SocialMediaMediator mediator) {

		this.mediator = mediator;
	}

	@Override
	public void post(String text) {

		System.out.println("Posting on Facebook : " + text);

		this.mediator.notifyMediator(this, text);
	}

	@Override
	public void postFromOtherMedia(String className, String text) {

		System.out.println();
		System.out.println("Facebook feed updated through " + className);
		System.out.println("Post is :" + text);
		System.out.println();

	}

}

As you can see whenever a post is posted on facebook through the post() method , the mediator is notified which in turns calls postFromOtherMedia() method of each social media account.

Twitter and Blog classes have similar code.

They all implement the same interface :

package behavioural.mediator.pattern;

public interface SocialMedia {

	public void post(String text);

	public void postFromOtherMedia(String className, String text);
}

Here is the output of the code :

Posting on Facebook : Celebrated my birthday today with family and friends!

Twitter feed updated through Facebook
Post is :Celebrated my birthday today with family and friends!


Blog feed updated through Facebook
Post is :Celebrated my birthday today with family and friends!

Posting on Twitter: Finished reading the book - The Art of Negotiation. Here is my review ...(link)


Facebook feed updated through Twitter
Post is :Finished reading the book - The Art of Negotiation. Here is my review ...(link)


Blog feed updated through Twitter
Post is :Finished reading the book - The Art of Negotiation. Here is my review ...(link)

Posting on Blog : The Writers Story : It was a lazy Sunday afternoon. The sun was hot and the writer took a walk down the street


Facebook feed updated through Blog
Post is :The Writers Story : It was a lazy Sunday afternoon. The sun was hot and the writer took a walk down the street


Twitter feed updated through Blog
Post is :The Writers Story : It was a lazy Sunday afternoon. The sun was hot and the writer took a walk down the street


That’s it!

Quoting the Gang of Four:

Define an object which encapsulates how a set of objects interact.

Mediator promotes loose coupling by keeping objects from referring to each other explicitly , and it lets you vary their interaction independently.

They call the SocialMediaMediator as ConcreteMediator (having an interface for the Social Media Mediator is optional)

and the social media classes (Facebook,Twitter, Blog) as ColleagueClasses.

Here is the code :

https://github.com/vijaysrj/designPatternsGoF/tree/master/src/behavioural/mediator/pattern

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s