Facade

提供Client一個簡單的介面,隱藏呼叫子系統的流程。

使用時機

  • 你想要減少子系統與客戶端程式的相依性,如此一來當子系統內部改變的時候,它的客戶端將不會受到影響。
  • 你希望子系統可以很容易地被使用。

from: Structural Patterns要解決什麼問題(上)?

from: Facade Pattern Tutorial with Java Examples

Example

Subsystem

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

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

Facade

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
    }
}

Client

public class Client {  
    public static void main(String[] args) {
        TravelFacade facade = new TravelFacade();
        facade.getFlightsAndHotels(from, to);
    }
}