Skip to main content

Behavioral Patterns - Mediator Pattern

The mediator pattern deals with the complexity which comes in the coding when number of classes increase. I will explain this. When we begin with development, we have a few classes and these classes interact with each other producing results. Now, consider slowly, the logic becomes more complex and functionality increases. Then what happens? We add more classes and they still interact with each other but it gets really difficult to maintain this code now. Mediator pattern takes care of this problem. It makes the code more maintainable. It promotes loose-coupling of classes such that only one class (Mediator) has the knowledge of all the classes, rest of the classes have their responsibilities and they only interact with the Mediator.

A very common example can be airplanes interacting with the control tower and not among themselves. The control tower knows exactly, where each of the airplanes is, and guides them whereas the airplanes have their own responsibilities of landing and takeoff. Another popular example is Stock exchange. In old days when there were no stock markets, the individual brokers used to buy or sell commodities among themselves. They used to face huge risks, of defaulting of counterparty, limited information (as, only limited deals in limited areas were possible), limited geographical reach, price variance (everyone could quote whatever price they wanted) and many more.

So, the concept of stock exchange came into play. For ex: BSE or NSE in India and NYSE, NASDAQ etc in the US. The stock exchange started acting like a mediator and the traders did not need to know other traders and services provided by them to make a deal. The traders have their own responsibilities as buyers and sellers and it was stock exchange’s responsibility to match their deals and get the settlement done. Many of the above mentioned risks were mitigated by this. But, there were some standardization procedures which came into picture because of this. All the traders who wanted to deal on stock exchange had to follow these standardization procedures.
Let’s look at the code part:
/**
* StockExchange – this is the mediator class
*/
public class StockExchange {

public static void doTransaction (String typeOfTransaction, int quantity, Scrip scrip, Trader trader) {


Transaction transaction = new Transaction(typeOfTransaction, quantity, scrip, trader);
// try and match the current transaction
// with the ones saved in DB and find out
// whether a counter transaction is there or
// are there many such transactions which could
// fulfill requirement of this transaction.
matchTransaction(transaction)

}
public static getPrice (Scrip scrip) {


// try and match this transaction with all
// the saved ones. If they match till whatever extent
// trade for that. Then save, with status Traded for
// number of shares traded and save the rest as New.

}
 
}// End of class

/**
* Trader1 – this trader wants to sell 100 shares of company XYZ
*/

public class Trader1 {

public void doTransaction (String typeOfTransaction, int quantity) {


int expectedPrice = 320;
Scrip scrip = new Scrip(“XYZ”);
int price = StockExchange.getPrice(scrip);
if(typeOfTransaction.equals(“SELL”)){



if(price >= expectedPrice){
StockExchange.doTransaction(“SELL”, 100, scrip, trader1);
}


}else if(typeOfTransaction.equals(“BUY”)){



if(price <= expectedPrice){
StockExchange.doTransaction(“BUY”, 100, scrip, trader1);
}


}

}

}// End of class

/**
* Trader2 – this trader wants to buyl 100 shares of company XYZ
*/

public class Trader2 {

public void doTransaction (String typeOfTransaction, int quantity) {


int expectedPrice = 320;
Scrip scrip = new Scrip(“XYZ”);
int price = StockExchange.getPrice(scrip);
if(typeOfTransaction.equals(“SELL”)){



if(price >= expectedPrice){
StockExchange.doTransaction(“SELL”, 100, scrip, trader2);
}


}else if(typeOfTransaction.equals(“BUY”)){



if(price <= expectedPrice){
StockExchange.doTransaction(“BUY”, 100, scrip, trader2);
}


}

}

}// End of class
This is simple illustration of how we can use a mediator. Here are the main features of a mediator:
• Responsibilities to individual objects.
• Mediator is the only smart delegating object.
• Transparency for other objects.
• If more objects join in, only place of registration is Mediator, other objects do not need to know anything about the new object.
• The code becomes very maintainable.
On hind side, this brings standardization, which might be cumbersome. Also, there might be a slight loss in efficiency.

Comments

Popular posts from this blog

Java Health Center - Overview and Features

This video highlights the features available in Health Center. Health Center is a low-processor and memory usage diagnostic tool for monitoring the status of a running IBM Java Virtual Machine (JVM). Health Center provides live information and recommendations in each of the following areas: - Classes: information about classes being loaded - Environment: details of the configuration and system of the monitored application - Garbage Collection: information about the Java heap and pause times - Locking: information about contention on inflated locks - Profiling: sampling profile of Java methods including call paths

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag...

Java Garbage Collection

Explain Garbage collection mechanism in Java? Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic pro...