Facade
Facade provides a new mechanism to combine the sub-systems and eventually provides an uniform interface to the client, which is a higher encapsulation and makes the sub-systems be used more easily, what's more? the sub-systems can run by themself and can be used independently.
This pattern is simple and i think every guy has used it in the system even they didn't know this pattern.
When we use this pattern
When we design our system. we are dedicated to abstract everything, so we got a lot of sub-systems and decouple them. But sometimes the client does not need to communicate each sub-system. the client needs to use the integration of some sub-systems. So the facade is used to integrate the expected sub-systems and provides a new interface to the client, the facade hides the detials of the sub-systems and the client even does not know the sub-systems. which is also the purpose of this pattern.
Roles in this pattern:
- Facade: hold the reference of the sub-systems which will be used in the facade. make the interface to the client and communicate with the client, it is some kind like the proxy of the sub-systems.
- Subsystem: do its own job and implement its own functions but hold nothing about the facade and also know nothing about the facade.
- Client.
Demo
namespace Facade { public class SubSystemOne { public void MethodOne() { Console.WriteLine("SubSystemOne:MethodOne"); } } public class SubSystemTwo { public void MethodTwo() { Console.WriteLine("SubSystemTwo:MethodTwo"); } } public class SubSystemThree { public void MethodThree() { Console.WriteLine("SubSystemThree:MethodThree"); } } public class SubSystemFour { public void MethodFour() { Console.WriteLine("SubSystemFour:MethodFour"); } } public class Facade { SubSystemOne one; SubSystemTwo two; SubSystemThree three; SubSystemFour four; public Facade() { one = new SubSystemOne(); two = new SubSystemTwo(); three = new SubSystemThree(); four = new SubSystemFour(); } public void MethodA() { one.MethodOne(); three.MethodThree(); four.MethodFour(); } public void MethodB() { two.MethodTwo(); three.MethodThree(); four.MethodFour(); } } class Client { static void Main(string[] args) { Facade facade = new Facade(); facade.MethodA(); facade.MethodB(); Console.Read(); } } }
Facade pattern decouples the relationship between the client and the sub-systems. Client doesnot need to care them and the sub-system just focuses on its own function. The client will not change with no change in the facade even some sub-systems changed.
The sub-systems can be used together in the facade and also can be used independently as a whole system.