Monday, December 01, 2003

Facade Pattern (Façade Pattern)


This is a very useful pattern. It is used to create a simple interface to a set of classes. Instead of having to deal with all the classes involved you just deal with the Facade class.


Let's say we have a set of classes that allow us to encrypt and decrypt byte streams. What we want to do is encrypt and decrypt files, folders and entire folder trees. Any application we create will have to deal with files, folders, trees and the byte streams, that's about 8 classes right there - encrypt file, decrypt file, encrypt folder, decrypt folder, encrypt tree, decrypt tree, encryption stream and decryption stream. Well maybe if you were only going to do this sort of thing once you could just do it and to hell with the complexity. But what if you were going to have to do it in several programs or even several places within the current program, and worse still, what if you built the whole complex mess and then had to modify it? This is looking ugly. So how can we simplify it?

We create a class that has a simple public interface and we put all the logic for dealing with the other classes into this "Facade". Now any application we create only has to deal with one class with a simple interface. It doesn't have to care about the details of files, streams, etc. Now if we have to make modifications we can change the internals of the many encrytion classes without affecting the client program at all.

Public Class CryptoFacade
Public Property Key() As String
Public Property Source() As String
Public Property Target() As String
Public Property Type() As String
Public Sub Encrypt()
Public Sub Decrypt()
End Class

We hide the other classes in the assembly by giving them "Friend" visibilty.

Friend Class EncryptFile
'code to encrypt a file
End Class
Friend Class DecryptFile
'code to decrypt a file
End Class

So the Facade class provides a sort of API to the other classes, thus keeping things simple for the client class that wants to use its functionality.


Wikipedia - Facade Pattern
Data & Object Factory - Facade Pattern
Bob Tarr University of Maryland - Facade Pattern
Bob Tarr - Design Patterns

No comments: