Introduction

Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to existing system to hide its complexities. This pattern involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes. It provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Intent

  • Provide a unified interface to a set of interfaces in a subsystem.
  • Define a higher-level interface that makes the subsystem easier to use.
  • Wrap a complicated subsystem with a simpler interface.

Implementation

Example

Let’s take a travel agent site for example, that allows you to book hotels and flights.

// HotelBooker
public class HotelBooker{  
  public ArrayList<Hotel> getHotelNamesFor(Date from, Date to){      
    //returns hotels available in the particular date range  
  }
}

// FlightBooker
public class FlightBooker{  
  public ArrayList<Flight> getFlightsFor(Date from, Date to){
    //returns flights available in the particular date range  
    }
}

// TravelFacade class allows the user to get their Hotel and Flight information in one call:
public class TravelFacade{   
  private HotelBooker hotelBooker;   
  private FlightBooker flightBooker;   
  
  public void getFlightsAndHotels(Date from, Data to)  {         
    ArrayList<Flight> flights = flightBooker.getFlightsFor(from, to);         
    ArrayList<Hotel> hotels = hotelBooker.getHotelsFor(from, to);         
  }
}

// All that the client needs to worry about is the Facade class: 
public class Client{   
  public static void main(String[] args)   {        
    TravelFacade facade = new TravelFacade();        
    facade.getFlightsAndHotels(from, to);  
  }
}