Like the Adapter pattern, Facade is known as a structural pattern, as it’s used to identifying a simple way to realize relationships between entities.
Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
The diagram definition of the Facade pattern is quite simple – all you’re really doing is insulating client from the subsystem:
So How Does It Work In Java?
Let’s put together a simple example in Java code to illustrate the pattern. Let’s take a travel agent site for example, that allows you to book hotels and flights.
We have a HotelBooker:
public class HotelBooker { public ArrayList<Hotel> getHotelNamesFor(Date from, Date to) { //returns hotels available in the particular date range } }
And a FlightBooker:
public class FlightBooker { public ArrayList<Flight> getFlightsFor(Date from, Date to) { //returns flights available in the particular date range } }
Both of these have Hotel and Flight datatypes, which the client has knowledge about. They could be provided in the same package as the Facade for example.
The 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); //process and return } }
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); } }
Downsides
By introducing the Facade into your code, you will be hardwiring subsystems into the Facade. This is fine if the subsystem never changes, but if it does, your Facade could be broken. Therefore, developers working on the subsystem should be made aware of any Facade around their code.
Adapter VS Facade
Similarity:
Like the adapter pattern, the Facade can be used to hide the inner workings of a third party library, or some legacy code. All that the client needs to do is interact with the Facade, and not the subsystem that it is encompassing.
Difference:
Facade defines a new interface, whereas Adapter uses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one. Adapter and Facade are both wrappers; but they are different kinds of wrappers. The intent of Facade is to produce a simpler interface, and the intent of Adapter is to design to an existing interface. While Facade routinely wraps multiple objects and Adapter wraps a single object; Facade could front-end a single complex object and Adapter could wrap several legacy objects.
Thanks to James Sugrue‘s artical: Design Patterns Uncovered: The Facade Pattern