Application Development, Product to Market
  • Home
  • Notes
  • Projects
  • Resources
    • Discovery Log
    • Books I Read
    • Blogs I Visit
    • Tools I Use
  • Home
  • Notes
  • Projects
  • Resources
    • Discovery Log
    • Books I Read
    • Blogs I Visit
    • Tools I Use

Mediator Design Pattern Example

10/21/2013

0 Comments

 
Mediator pattern is a behavioral pattern that coordinates and encapsulates many-to-many communication/interaction among related objects (Colleagues) so that Colleagues interact not directly with other independent Colleagues, but indirectly with other Colleagues through a centralized Mediator.
Picture
source: GoF
Each Colleague references the Mediator. In reverse, the Mediator references the registered Colleagues.
Picture
Object Structure, source: GoF

overview

Mediator pattern involves two abstraction trees - Mediator inheritance hierarchy and Colleague inheritance hierarchy. All Colleagues should interact with the mediator object, instead of each other.

Think of Mediator as a centralized traffic controller or a stock exchange where participating brokerages have their buy/sell orders fulfilled.

To loosely couple participating objects (Colleagues), the Mediator object must encapsulates and keep references to all participating objects (Colleagues). One way of achieving this is to provide methods (e.g. Mediator.addXXXX(Colleague) or Mediator.registerXXXX(Colleague)) for registering Colleagues. The timing of registering a Colleague can be when a Colleague is constructed.

Once registered with the Mediator, Colleagues are either consumer or producer. Each participating Colleague object encapsulates a Mediator through its constructor. When a Colleague is constructed, it register itself with the Mediator. When a Colleague object’s internal state changes through operation (e.g. calling sellOffer()), it delegates and reports that state change to the Mediator by calling Mediator.sellOffer() that goes through multiple participated Colleagues registered with the Mediator, acting something like a controller in Model/View/Controller architecture.

mediator design pattern code example

The following source are taken from New Think Tank by Derek Banas. Please visit his blog and support his awesome work.
public class StockOffer{
  
  private int stockShares = 0;
  private String stockSymbol = "";
  private int colleagueCode = 0;
  
  public StockOffer(int numOfShares, String stock, int collCode){    
    stockShares = numOfShares;
    stockSymbol = stock;
    colleagueCode = collCode;    
  }
  
  public int getstockShares() { return stockShares; }
  public String getStockSymbol() { return stockSymbol; }
  public int getCollCode() { return colleagueCode; }
  
}
Colleague:
Register Colleague with Mediator.public abstract class Colleague{
  
  private Mediator mediator;
  private int colleagueCode;
  
  public Colleague(Mediator newMediator){ 
    mediator = newMediator;   
    mediator.addColleague(this);    // 1
  }
  
  public void saleOffer(String stock, int shares){
    mediator.saleOffer(stock, shares, this.colleagueCode); // 2
  }
  
  public void buyOffer(String stock, int shares){
    mediator.buyOffer(stock, shares, this.colleagueCode);
  }
  
  public void setCollCode(int collCode){ colleagueCode = collCode; }
}



public class GormanSlacks extends Colleague{
  public GormanSlacks(Mediator newMediator) {
    super(newMediator);
    System.out.println("Gorman Slacks signed up with the stockexchange\n");  
  }  
}

public class JTPoorman extends Colleague{
  public JTPoorman(Mediator newMediator) {
    super(newMediator); 
    System.out.println("JT Poorman signed up with the stockexchange\n");
  }  
}
[1] Register Colleague with Mediator.
[2] Delegate change/operation to Mediator.

Mediator:
public interface Mediator {  
  public void saleOffer(String stock, int shares, int collCode);  
  public void buyOffer(String stock, int shares, int collCode);
  public void addColleague(Colleague colleague);  
}


public class StockMediator implements Mediator{

  private ArrayList<Colleague> colleagues;       // 1
  private ArrayList<StockOffer> stockBuyOffers;  // 2
  private ArrayList<StockOffer> stockSaleOffers; // 2 
  private int colleagueCodes = 0;
  
  public StockMediator(){    
    colleagues = new ArrayList<Colleague>();
    stockBuyOffers = new ArrayList<StockOffer>();
    stockSaleOffers = new ArrayList<StockOffer>();
  }
  
  public void addColleague(Colleague newColleague){    
    colleagues.add(newColleague);                // 3
    colleagueCodes++;    
    newColleague.setCollCode(colleagueCodes);   
  }
  
  public void saleOffer(String stock, int shares, int collCode) {
    boolean stockSold = false;    
    for(StockOffer offer: stockBuyOffers){      
      if((offer.getStockSymbol() == stock) && (offer.getstockShares() == shares)){       
        System.out.println(shares + " shares of " + stock + 
            " sold to colleague code " + offer.getCollCode());        
        stockBuyOffers.remove(offer);        
        stockSold = true;        
      }       
      if(stockSold){ break; }      
    }
    
    if(!stockSold) {      
      System.out.println(shares + " shares of " + stock + 
          " added to inventory");     
      StockOffer newOffering = new StockOffer(shares, stock, collCode);     
      stockSaleOffers.add(newOffering);      
    }  
  }

  public void buyOffer(String stock, int shares, int collCode) {    
    boolean stockBought = false;
    
    for(StockOffer offer: stockSaleOffers){     
      if((offer.getStockSymbol() == stock) && (offer.getstockShares() == shares)){        
        System.out.println(shares + " shares of " + stock + 
            " bought by colleague code " + offer.getCollCode());        
        stockSaleOffers.remove(offer);        
        stockBought = true;        
      } 
      
      if(stockBought){ break; }      
    }
    
    if(!stockBought) {    
      System.out.println(shares + " shares of " + stock + 
          " added to inventory");      
      StockOffer newOffering = new StockOffer(shares, stock, collCode);      
      stockBuyOffers.add(newOffering);      
    }    
  }

  public void getstockOfferings(){
    System.out.println("\nStocks for Sale");
    
    for(StockOffer offer: stockSaleOffers){      
      System.out.println(offer.getstockShares() + " of " + offer.getStockSymbol());      
    }
    
    System.out.println("\nStock Buy Offers");
    
    for(StockOffer offer: stockBuyOffers){      
      System.out.println(offer.getstockShares() + " of " + offer.getStockSymbol());      
    }    
  }
  
}
[1] Encapsulate with references to participating Colleague.
[2] Inter-communication is encapsulated by Mediator.
[3] The code called by Colleague's constructor that actually registers a colleague.

when to use mediator design pattern

  • Promote many-to-many relationship network.
  • The complexity of object communication begins to hinder object reusability.
  • You want some sort of object which sets up publish and subscribe functionality. 
  • The behavior that's distributed between several classes should be customizable without a lot of subclassing.

references

  • Mediator Design Pattern

0 Comments



Leave a Reply.

    Categories

    All
    Algorithm
    Concurrency
    CQ
    Data Structure
    Design Pattern
    Developer Tool
    Dynamic Programming
    Entrepreneur
    Functional Programming
    IDE
    Java
    JMX
    Marketing
    Marklogic
    Memory
    OSGI
    Performance
    Product
    Product Management
    Security
    Services
    Sling
    Social Media Programming
    Software Development

    Feed Widget

    Archives

    May 2020
    March 2020
    April 2018
    March 2018
    February 2018
    December 2017
    March 2017
    November 2016
    June 2016
    May 2016
    April 2016
    October 2015
    September 2015
    August 2015
    September 2014
    July 2014
    June 2014
    May 2014
    March 2014
    January 2014
    December 2013
    November 2013
    October 2013
    September 2013
    August 2013
    July 2013
    June 2013

    RSS Feed

in loving memory of my mother  and my 4th aunt
Photos used under Creative Commons from net_efekt, schani, visnup, Dan Zen, gadl, bobbigmac, Susana López-Urrutia, jwalsh, Philippe Put, michael pollak, oskay, Creative Tools, Violentz, Kyknoord, mobilyazilar