Monday, May 14, 2012

Structural Patterns - 5.Facade Pattern

Facade is an exterior view/face of a building. We can understand the whole structure of the building by its exterior view.

But internally, they have lot of rooms, wiring, plumbing, interior decorations,etc., which we may not interested to know.

Day to day we deal with complex business functionalities. We seperate our business requirements into different classes and maintain the inter-operability between them.

We should be able to re-use such components within our application or from an external application whenever there is a need.

Our component may have a complex design with many business processings but we need to provide a simpler interface for other systems to use it. Such type of an interface is a Facade.
A railway reservation system is a complex process involving hundreds of rules or policies while booking a ticket. They have seperate systems to handle the list of stations,trains,quotas,preferences,etc.

We may not have much interest over the internal happenings of the system. We will end up in providing the details about the passenger and the seat preference.

The system will perform the complex processing and generate the ticket for us based on the data provided.


The following class diagram explains the Facade pattern,



Here, the Ticket class offers a simple method bookTicket() which is the facade for the complex ticket reservation process.

 A single call to the bookTicket() will communicate with different systems like stations, preferences, ticket classes, quotas, etc., and generates the ticket for the passenger.

Refer the following code snippet for more details,

// Constructor 

  public Ticket() {
     stations=new Stations();
     train=new Train();
     quota=new Quota();
     preference=new Preference();
 }


// Facade for booking the ticket

public void bookTicket(){
 ticket.setClass(train.getTravelClass());
 ticket.setFromStation(stations.getFrom());
 ticket.setToStation(stations.getTo());
 ticket.setPreference(preference.getPreference());
 ticket.setQuota(quota.getQuota());
 ticket.generate();
}

No comments:

Post a Comment