The fifth design pattern in the Structural Category is the Facade Design Pattern. Let's take a look on what is this design pattern for and how do we implement it in C# and .Net.
Note: Code can be downloaded at my Github.
1. What is the Facade Design Pattern?
The Facade Design Pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a high level interface that makes the subsystem easier to use.
Facade is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes.
2. When to implement the Facade Design Pattern?
The Facade Design Pattern may be used unknowingly in your project even you are not aware of this. This is one of the most useful design pattern which helps your project architecture better if you understand it thoroughly.
You may want to implement the Facade Design Pattern when:
- You want to provide a simple interface to a complex subsystem. Subsystems often get more complex as they evolve.
- There are many dependencies between clients and the implementation classes of an abstraction.
- You want to layer the subsystems. Use a facade to define an entry point to each subsystem level.
3. How to implement the Facade Design Pattern?
Let's take an example of an application involving payment which has a Product, a Payment, and an Invoice class.
Step 1: Examine the Subsystems
The existing system has 3 subsystems as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class Payment { public void MakePayment() { Console.WriteLine( "Payment Proceeded Successfully!" ); } } public class Invoice { public void SendInvoice() { Console.WriteLine( "Invoice Sent Successfully!" ); } } |
Step 2: Create a Facade class
Creating an OrderFacade class to make a gateway to all subsystems:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class OrderFacade { public void PlaceOrder() { Console.WriteLine( "---Ordering Proccess Started---" ); Product p = new Product(); p.GetProductDetails(); Payment pmt = new Payment(); pmt.MakePayment(); Invoice inv = new Invoice(); inv.SendInvoice(); Console.WriteLine( "Order Placed Successfully!" ); Console.WriteLine( "---Ordering Proccess Ended---" ); } } |
Done! So now in your client, you don't need to directly access the subsystems, instead, you can just use the Facade to let it process your subsystems internally.
1 2 3 4 5 6 7 8 | class Program { static void Main( string [] args) { OrderFacade o = new OrderFacade(); o.PlaceOrder(); } } |
Output
4. Conclusion
The Facade Design Pattern is a way to simplify your complex systems to make it easier for the client to use. I hope this tutorial is helpful and please let me know your thoughts by commenting this the section below. See you next time!