facade的另一个例子:
假设你的应用程序连接到数据库,并在UI上显示结果。可以使用facade使应用程序可配置,就像使用数据库或模拟对象运行一样。因此,您将对facade类进行所有的数据库调用,在那里它将读取app配置并决定触发db查询或返回模拟对象。这样,在数据库不可用的情况下,应用程序成为独立于db的。< / p >
import java.util.*;
public class TravelFacade{
FlightBooking flightBooking;
TrainBooking trainBooking;
HotelBooking hotelBooking;
enum BookingType {
Flight,Train,Hotel,Flight_And_Hotel,Train_And_Hotel;
};
public TravelFacade(){
flightBooking = new FlightBooking();
trainBooking = new TrainBooking();
hotelBooking = new HotelBooking();
}
public void book(BookingType type, BookingInfo info){
switch(type){
case Flight:
// book flight;
flightBooking.bookFlight(info);
return;
case Hotel:
// book hotel;
hotelBooking.bookHotel(info);
return;
case Train:
// book Train;
trainBooking.bookTrain(info);
return;
case Flight_And_Hotel:
// book Flight and Hotel
flightBooking.bookFlight(info);
hotelBooking.bookHotel(info);
return;
case Train_And_Hotel:
// book Train and Hotel
trainBooking.bookTrain(info);
hotelBooking.bookHotel(info);
return;
}
}
}
class BookingInfo{
String source;
String destination;
Date fromDate;
Date toDate;
List<PersonInfo> list;
}
class PersonInfo{
String name;
int age;
Address address;
}
class Address{
}
class FlightBooking{
public FlightBooking(){
}
public void bookFlight(BookingInfo info){
}
}
class HotelBooking{
public HotelBooking(){
}
public void bookHotel(BookingInfo info){
}
}
class TrainBooking{
public TrainBooking(){
}
public void bookTrain(BookingInfo info){
}
}
解释:
FlightBooking, TrainBooking and HotelBooking是大系统的不同子系统
TravelFacade提供了一个简单的界面来预订以下选项之一
Flight Booking
Train Booking
Hotel Booking
Flight + Hotel booking
Train + Hotel booking
book API from TravelFacade internally calls below APIs of sub-systems
In this way, TravelFacade provides simpler and easier API with-out exposing sub-system APIs.
Key takeaways : ( from journaldev article by Pankaj Kumar)
Facade pattern is more like a helper for client applications
Facade pattern can be applied at any point of development, usually when the number of interfaces grow and system gets complex.
Subsystem interfaces are not aware of Facade and they shouldn’t have any reference of the Facade interface
Facade pattern should be applied for similar kind of interfaces, its purpose is to provide a single interface rather than multiple interfaces that does the similar kind of jobs
Have a look at sourcemaking article too for better understanding.