Monday, January 5, 2015

Mediator Design Pattern

Type : Behavioral Design Pattern

Summary : 

Mediator Design pattern provides a common a platform for communication between different objects.
It promotes loose coupling between interacting objects. In a complex software where number of Classes interacting with each other are more, using Mediator Design pattern is very useful. As Mediator will reduce the complexity  of objects interacting with each other to a centralized Mediator, which results in easy maintenance of code.

Advantages :

Centralizes the interaction between many objects which is easy to maintain.
Promotes decoupling the interacting objects.

Participants :

Concrete Mediator
Concrete Colleague 

Example :

For our example,  we will consider the example of playing week's most popular new release on home theater entertainment system. We will consider that playing a movie depends on a number of systerms\services.

Let's assume the followings,
We have a website which gives us the name of the most popular new release.
We have a steaming service which can play the Movies
We have a home theater, that is TV+Music System.

We we consider the following classes like TV:turnonTV  Homethreater:turnonHomeTheater, Website:getMostPopularMovieOfWeek and TV:getMovie(Movietitle)

It is clear that many classes and different methods need's to be invoked in order to start the show.

We can have a mediator like following.

Movie movieTitle = IMDB:getWeeklyPopularMovie();
Movie playMovie = NetFlix::getMovie(movieTitle);

if(!playMovie) playMovie = AmaxonStreaming::getMovie(movieTitle);


This example demonstrates how the introduction of Mediator simplifies the interaction between different classes. For instance later if we want to Change the Media source from NetFlix to Something else, we just need to update the StartShowMediator, without or with very minimum code changes elsewhere.

No comments :

Post a Comment