The Facade design pattern provides a simple interface to a complex code in order to make the product easier to understand and use. This design pattern reduces the dependency of client code on the implementation of internal objects and since most of the product code uses the facade to hide the complexity of the system, thus allows the flexibility in developing the system. In this pattern, a single wrapper class known as “Facade” is implemented which contains a set of objects required by client. For Design patterns basic explanation see (Design Patterns Simplified Version).
Generic model class diagram of Decorator design pattern is as shown in image.
Facade Design Pattern Code Example:
Let’s take a very basic example of a hi-tech house where all the home appliances are connected through remote controls, so to turn on any equipment we just need to press remote control’s On/Off button. Now, when you leave the house then all the lights, fans, AC etc you have to switch off every one of them which is a tedious and boring job. In this example, we can define a “Facade” class which will take care of all these scenarios. Class diagram for the solution of this problem is as shown in image.
Let’s have a look on the class definition to handle various home appliance product.
class TeleVision { public: void switchOn() { cout<<"TeleVision Switched ON"<<endl; } void switchOff() { cout<<"TeleVision Switched OFF"<<endl; } }; class SecuritySystem { public: void switchOn() { cout<<"SecuritySystem Switched ON"<<endl; } void switchOff() { cout<<"SecuritySystem Switched OFF"<<endl; } }; class Refrigerator { public: void switchOn() { cout<<"Refrigerator Switched ON"<<endl; } void switchOff() { cout<<"Refrigerator Switched OFF"<<endl; } }; class RoomHeater { public: void switchOn() { cout<<"RoomHeater Switched ON"<<endl; } void switchOff() { cout<<"RoomHeater Switched OFF"<<endl; } };
Now, Let’s have a look on the Facade class which will handle switching On/Off of home appliances whenever we go out or come back.
class RoomFacade { private: TeleVision m_tv; SecuritySystem m_securitySystem; Refrigerator m_refrigerator; RoomHeater m_roomHeater; public: void goingOut() { cout<<"Going out for a walk"<<endl; m_tv.switchOff(); m_securitySystem.switchOn(); m_refrigerator.switchOff(); m_roomHeater.switchOff(); } void comingBack() { cout<<"Coming back to home"<<endl; m_tv.switchOn(); m_securitySystem.switchOff(); m_refrigerator.switchOn(); m_roomHeater.switchOn(); } };
Let’s see now how to use the above described classes to build the final product. Below code is sample “main” function code.
int main() { RoomFacade room; room.goingOut(); room.comingBack(); }
Output of the above given example:
Going out for a walk TeleVision Switched OFF SecuritySystem Switched ON Refrigerator Switched OFF RoomHeater Switched OFF Coming back to home TeleVision Switched ON SecuritySystem Switched OFF Refrigerator Switched ON RoomHeater Switched ON