Sunday, 18 November 2012

The Facade Pattern in .NET

The Facade Pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.

The Facade Pattern is the simplest of the patterns and it is something that many developers probably used a lot in the past without even knowing that there was a name for it. 

It is all about creating a class that simplifies and unifies a set of more complex classes that belong to some subsystem. However a Facade typically does not hide the complex subsystem but simply provide a different simplified view of it. This means that is always possible to use the complex subsystem when needed and that is theoretically possible to have multiple Facades per subsystem.

This pattern typically use the technique of "wrapping" to accomplish the goal. It is important however to remember that the intent of the pattern is to reduce complexity and not to adapt different interfaces like the Adapter Pattern.

I think that it is not worth creating an artificial example to showcase the Facade Pattern. It is more valuable to show examples of usage in the .NET Framework.

A primitive way to implement a Facade is using a static class.

The most significant example in .NET is surely the class File that provide a simple way to interact with the file system in a very intuitive way instead of using lower level abstractions like streams.


This method hides a lot of complexity. If you look inside the .NET Framework source code you find something similar to this:


An another example of Facade in the framework is the class WebClient that allows to easily download a web page from a server without dealing with the HTTP protocol and the sockets.

The beauty of the pattern is then in its simplicity and obviousness.

In addition of simplifying the access to a subsystem the pattern allows to decouple your client implementation from the subsystem. If future version of the subsystem changes the internal components this will not require to update the client code assuming that the Facade API remains unchanged.


No comments:

Post a Comment

What you think about this post? I really appreciate your constructive feedback (positive and negative) and I am looking forward to start a discussion with you on this topic.