Façade Pattern
What is Façade pattern?
The
Facade Pattern provides a unified interface to a set of interfaces in as
subsystem. Facade defines a higher-level interface that makes the subsystem
easier to use.
Why needs Façade pattern?
Needs
a
simplified interface to the overall functionality of a complex subsystem
How to implement Façade pattern?
/* Complex parts */
class CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}
class Memory {
public void load(long position, byte[] data) { ... }
}
class HardDrive {
public byte[] read(long lba, int size) { ... }
}
/* Facade */
class Computer {
private CPU processor;
private Memory ram;
private HardDrive hd;
public Computer() {
this.processor = new CPU();
this.ram = new Memory();
this.hd = new HardDrive();
}
public void start() {
processor.freeze();
ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR,
SECTOR_SIZE));
processor.jump(BOOT_ADDRESS);
processor.execute();
}
}
/* Client */
class Client {
public static void main(String[] args)
{
Computer facade = new Computer();
facade.start();
}
}
Another example
Conclusion
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
}
}
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
}
}
public class Client {
public static void main(String[]
args) {
TravelFacade
facade = new TravelFacade();
facade.getFlightsAndHotels(from,
to);
}
}
A
facade can accomplish all of the following.
•Make a
software library easier to use and understand.
•Make code
that uses the library more readable.
•Reduce
dependencies
of outside code on the inner workings of a library.
•Wrap a
poorly designed collection of APIs with a single well-designed API.
0 comments:
Post a Comment