Design Patterns – Facade

The Facade Pattern is used to provide a simplified interface to a complicated subsystem.

The idea is to define a higher-level interface that abstracts clients from using directly a set of lower level interfaces in the subsystem. For some clients accessing directly the subsystem could make perfect sense because they benefit from the different options and flexibility of a rich API. However, most of the clients only need basic functionality, accessing a large set of interfaces only bring them complexity.

This pattern is commonly used during refactoring to simplify the use of a legacy code subsystem.

One important difference between this structural pattern and the Decorator pattern is that the goal in Facade is not to add new functionality.

Real examples

* JQuery
JQuery is a good example of Facade Pattern, providing a simple and clean interface to interacting with the complex DOM of the browser.

* Java URL class

URL url = new URL("http", "www.google.ie", 80, "/";);
url.openStream()

https://docs.oracle.com/javase/8/docs/api/java/net/URL.html

Code example

class FlightsService {
  findFlightsFor(city, date) {
    console.log(`Searching for flight to ${city} on ${date}`);
  }

  book(flightNumber, airline, date) {
    console.log(`Booking flight ${flightNumber} - ${airline} on ${date}`);
  }
}

class HotelsService {
  findHotelsFor(city, checkinDate, checkoutDate) {
    console.log(`Searching for hotels on ${city} from ${checkinDate} to ${checkoutDate}`);
  }

  book(roomNumber, hotel, checkinDate, checkoutDate) {
    console.log(`Booking room ${roomNumber} - ${hotel} from ${checkinDate} to ${checkoutDate}`);
  }
}

class TravelFacade {
  constructor() {
    this.flightsService = new FlightsService();
    this.hotelsService = new HotelsService();
  }

  findFlightsAndHotels(city, travelDate, returnDate) {
    this.flightsService.findFlightsFor(city, travelDate);
    this.flightsService.findFlightsFor(city, returnDate);
    this.hotelsService.findHotelsFor(city, travelDate, returnDate);
  }
}

Documentation

https://en.wikipedia.org/wiki/Facade_pattern
http://www.joezimjs.com/javascript/javascript-design-patterns-facade/
https://dzone.com/articles/design-patterns-uncovered-1
http://www.dofactory.com/javascript/facade-design-pattern

Advertisements