January 4, 2011 Design Patterns
January 4, 2011 Design Patterns
Facade is design pattern that provides us with one entry point to subsystem, simplifying its usage and understanding.
In our example facade would be terminal-serving station (SkiResortFacade), subsystem would be whole bunch of renting buildings, paydesks, hotels. Of course we can go all around the resort, if we like this, but if we take a look from software development point of view if devs will walk all around and use as they wish, it will not lead to positive consequences. And skiers-newcomers will never know where they should go for the first time.
internal class SkiRent { public int RentBoots(int feetSize, int skierLevel) { return 20; } public int RentSki(int weight, int skierLevel) { return 40; } public int RentPole(int height) { return 5; } } internal class SkiResortTicketSystem { public int BuyOneDayTicket() { return 120; } public int BuyHalfDayTicket() { return 60; } } internal class HotelBookingSystem { public int BookRoom(int roomQuality) { switch (roomQuality) { case 3: return 250; case 4: return 500; case 5: return 900; default: throw new ArgumentException("roomQuality should be in range [3;5]","roomQuality"); } } } public class SkiResortFacade { private SkiRent _skiRent = new SkiRent(); private SkiResortTicketSystem _skiResortTicketSystem = new SkiResortTicketSystem(); private HotelBookingSystem _hotelBookingSystem = new HotelBookingSystem(); public int HaveGoodOneDayRest(int height, int weight, int feetSize, int skierLevel, int roomQuality) { int skiPrice = _skiRent.RentSki(weight, skierLevel); int skiBootsPrice = _skiRent.RentBoots(feetSize, skierLevel); int polePrice = _skiRent.RentPole(height); int oneDayTicketPrice = _skiResortTicketSystem.BuyOneDayTicket(); int hotelPrice = _hotelBookingSystem.BookRoom(roomQuality); return skiPrice + skiBootsPrice + polePrice + oneDayTicketPrice + hotelPrice; } public int HaveRestWithOwnSkis() { int oneDayTicketPrice = _skiResortTicketSystem.BuyOneDayTicket(); return oneDayTicketPrice; } } public class FacadeDemo { public static void Run() { var skiResortFacade = new SkiResortFacade(); int weekendRestPrice = skiResortFacade.HaveGoodOneDayRest(175, 60, 42, 2, 3); Console.WriteLine("Price: {0}", weekendRestPrice); } }
This design pattern in some way represents very important encapsulation principle but just on higher level. On this level we encapsulate whole subsystem instead of class. Big systems usually consist with many subsystems that communicate between each other by using facades. Space station connects to another station using one mechanism, not with gluing together hundreds of wires and tubes. Also an good way to develop software would be to have some kind of facade (it might be set of known interfaces) inside of each assembly, so it can be used easily from other parts of your application.
Thank you.
My design patterns table
code
more code
~~~~