Pages

Saturday, January 29, 2011

The Facade design pattern

Sorry that it’s been so long since my last post. After finishing my book, I needed to take some time to catch up on some projects that needed some attention. Plus, my Call of Duty game needed some attention as well.

Anyway, on with the post.

The first design pattern that I’s like to cover is called the Facade. Just as an architectural facade is the face of a building, a software facade is the face of a class or set of classes. Designers use the Facade pattern to cover over or conceal the actual interface used to talk to a class. Often times, a Facade is used to provide a simple interface to a class that has a complex interface. You can also use a Facade to provide a consistent interface, or set of methods, to a class that may change.

Imagine that you are designing a software library for talking to a database. You know that you will need to expose methods for calling Insert, Update and SQL execution functions. In order to call these functions, you need to use specific function calls that are exposed by the database. At the beginning of the project, you are told that you are going to use an Oracle database, but you know that the customer is fickle and may change the database on you at any time. This is the perfect time to use a Facade.

You could design a database facade class that exposes some general database methods like insert, update and execute. Then, you can code the facade to use the appropriate calls for your chosen database. All of the code in your project that needs to talk to the database will be coded to talk to the Facade and use the general methods that you have defined.

FacadePattern-2011-01-29-11-34.jpg

The beauty of the pattern becomes evident when the customer decides to change the database. Instead of changing the database calls all over your application, you need only change the facade. The facade hides the complexity of it’s underlying classes and exposes a common set of methods that any user of the class would need. The users of your database facade won’t care if they are pointed to an Oracle, MySQL or SQLite database. All that they will need to know is the interface that is exposed by your facade.

So, when you are designing a system where the underlying pieces may change, consider using a Facade. Using this pattern will save you time and effort when your customer changes his or her mind, which they are apt to do.