Tutorial Design Patterns - Structural patterns

Facade pattern

Overview

Difficulty and Complexity
Degree of Difficulty 1
Structural Complexity 2
Extra-Pattern Complexity 9
Implementation Specificity 9


Intent according to the GoF
"Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes a subsystem easier to use" [GoF 94]

Intent seen through Real Life
A poignant example of Facade pattern is the paying of protection money to criminal master-minds.

How much more blunt and abrupt do you want me to be?

Let me say again, paying protection money is a facade.

Let's look at facades from four angles. As relate to buildings, as relate to the impression people create, as relate to paying protection money and as relate to the Facade pattern.

A facade on a building adds a sense of complexity to the building. Usually it is decorative so that the building's look is enhanced and looks more architecturally complex. This is actually the opposite of what the facade pattern achieves since it makes a structure look much simpler.

When a person puts up a facade, they are usually creating a false impression for others to be fooled by. Concentrating intently on a solitaire game as your boss walks by your office is a facade. Your boss thinks her company is being very productive while you un-productively run up her health-care costs (since you will need glasses sooner due to your decreased "blink-rate").

The paying of protection money gives you the false impression that everything is ok. Business people pay over a significant portion of their operating profits every month to some gang-leader who convinces them that it's the only way to save their business from being burnt down, being held up, their employees being mugged and raped etc. The thinking is that by paying money to one criminal, that one person negotiates with all the other low-lifes and demand their obedience in leaving some people alone and only being allowed to terrorise and murder the others who haven't "paid up". And I say terrorise because that is what they are, terrorists. They threaten the very existence of the state since it seems easier to deal with the gangster currently reigning (their lives being as short as they are) since the consequences are more immediate, than paying your taxes.. They scurry around like bin-laden under the cover of caves and so are hard to detect since they terrorise the communities they "rule over", exacting their own perverse justice on "informers" who challenge their rule. They drive down property values, make the communities they live in undesirable, prevent children from going to school so they can tempt them with ill-gotten short-term gains. And finally they choke into loss, the very businesses which pay them protection money, since customers avoid the gang-war torn areas and sales go right down to nothing. So they are no better than cancers which spread and rob the life of the very host which keeps them alive.

Paying protection money is like being led from underneath and from behind, no better than a modern form of slavery, supporting a slave master who drives a car ten times nicer than the cars that the legitimate business "owners" can ever aspire to. And paying extortion money is just one of the techniques we practise while in bed with the devil. We pay for our own safety at the cost of funding other people's assassinations and the demise of the state we live in. In fact extortionists should be legislated into the same category as terrorists. Because they do two things consistent with terrorism. They drive terror into people while lurking in the shadows and undermining the control of governments, all the time deepening the roots of criminality with their gang-initiation based rapes and murders. They also siphon off tax and taxable dollars which could have gone into welfare systems which would have helped support the very people from the ghetto whom they "rule" over and claim to help. The joke is that the same people who are forced to demonstrate when a gang leaders is arrested, are the same people who are required to send their 13 year old daughters to the gang leaders so they can rape, impregnate and infect them with diseases. On the whole, extortionists are agents of the devil himself who perpetuate a cycle of depravation, indignity, rape and terror.

Whew !!! I apologize for using such a negative introduction to the pattern but by now you have a sense that I feel burdened to do a little social engineering mixed in with the software engineering. Anyway I'm not here to preach (that would actually cost you extra :).

The tax office is a positive example of the facade system. It allows you to pay for many government-provided services at the same time when you pay taxes. Every month, you pay water bills, electricity bills, phone bills, heating bills and so on to private companies. The government streamlines all the bill payments for all the services it provides and instead of paying for roads, police services, education services, diplomatic services and others, you pay one tax and all of this is covered. Now many of you may pay highway tolls, send your children to private schools and may employ private security guards. You have decided that the generalized services provided by the government are not at the standard you desire. That's fine. The point is that in the general case which is sufficient for most citizens/residents, the payment to the Revenue service allows you to pay for all those government services in one go.

The Facade pattern is like the IRS in the tax collection and disbursement system. The pattern suggests that when clients have to interact with several classes or subsystems, we can generally provide a single class which acts as a buffer between the client-class and the classes/sub-systems which provide do work for it. This is not to say that the client-class is disallowed from interacting with the worker-classes. It just means that the interaction with worker classes is streamlined down to interacting with one class. There is usually one method in the Facade class which knows how to perform work that most clients want done and this work is done by executing several methods on several of the sub-system classes which we are preventing the client from having to interact with. So in most instances, the client has to call just one method on the facade class, which will then take over and do what it needs done using the services of several sub-system classes.

So the Facade class is like the IRS as you can imagine. Most clients will get the majority of their work done through simply paying their taxes and voting. The rest of governance (hopefully) happens seemlessly. If you hear a strange noise in the night, you simply call 911 and give your location. The police don't need to look up your tax payment records and figure out whether you're a "paid-up-customer". They simply rush on over and intercept any baddies trying to disrupt your life, alerting the fire and ambulance services at the same time if necessary (and so in a sense a 911 call is itself another demonstration of the Facade pattern).

Naturally the tax-paying citizen is the client in the situation, just as the client in the pattern is any code which wants to get work done through the Facade class.

Finally, the government bodies and agencies such as garbage collection, policing, schools, hospitals and road-building are like the worker-classes/sub-system classes in the facade pattern. They do the actual work which the client is interested in, but they do it without the client having to interact with them or know the specifics of how they do their work.

Intent seen through O/S & Applications
The GoF book speaks to compilers being facades since a lot of stuff goes on behind the compilation. And so if you hit the start button while editing a program in visual Studio, you will see a pretty good example of the pattern.

Like the GoF example, A good example of Facade is the VB.NET IDE. Hitting the run button not only parses, error checks and builds and compiles the code in the background, it also saves any unsaved changes and finally runs the program so you can see if it runs error-free.

But like a true facade, this does not hide the functionality which it represents. This is important since you might be debugging some code but have not finished all the debugged. You cannot run the code without having a fully bug free version. If you could only save the code while running it, then you would not be able to stop debugging until all bugs were out. This would of course result in lots of lost code-changes or lots of missed lunches (which the boss wouldn't mind right? In fact I can see a lot of bosses saying "Hmmm, nice idea, I need to call Microsoft about VS2007"). And supposing you wanted to build without actually running the code since you have a database which needs to be backed up before being modified in the test-run. Well if all the functionality was lumped into that one start button on the debug menu, you would lose a lot of flexibility. So like the facade, one touch buttons must-not hide the functionalities they group together, just give you a quick access to a group of them. So you get the best of both worlds, flexibility of being able to perform single chores while being able to perform all related chores in a one-touch fashion.

http://www.programmersheaven.com/articles/designpatterns/image035.gif

Scenario - Sample Code
The scenario for the sample code is that of a travel agent. Booking a vacation can be a stressful and error-prone thing to do. There are lots of things to get right, lots of little pieces to fit. Lots of things to take into account and lots of things to go wrong. I was going on a training course once and was supposed to stop over in Miami before heading to Toronto. The pilots of the airline on which I was supposed to make this hop were striking. And because of that I ended up on Air Canada which was nice, especially since I got to hear a little French, my favourite language (of which I know 2 or 3 words). Even nicer than that was the non-stop flight to Canada. So that particular hiccup worked out nicely since one-stop turned to non-stop. But hiccups can go the other way. And instead of taking you quickly north, the trip can go disastrously south. And because of that we use travel agents who make all these arrangements for us and ensure that we are protected from the vagaries of trip-planning.

So that's what the Facade class does in our sample code. Except that my knowledge of the travel industry is so limited I might embarrass myself if I put in too much code. So the program simply makes a bunch of method calls but doesn't really do anything. In the end the point of the sample-code is to make you think of all the classes you would have to interact with in planning a vacation and makes you see how thankful client -coders would be once that functionality is already coded and grouped together in a convenient "one-touch" method call. That's all the Facade pattern does and if you get that idea, then that's enough.

The Meat of the Matter

UML - General
http://www.programmersheaven.com/articles/designpatterns/image036.gif

UML - Sample Code
http://www.programmersheaven.com/articles/designpatterns/image037.gif

Participants - Sample Code
Subsystem Classes - VisaRequirementsChecker, FlightBooker, HotelBooker, ReggaeConcertBooker, SportingEventBooker, PartyBooker

Little worker classes which each do a little piece of the work to be done. They can be referenced directly, not only through the Facade. Also, they make no reference to the Facade classes since they are unware of the Facades.

Facade - FacadeA_AffordableVacationPlanner, FacadeB_ExpensiveVacationPlanner

Know how to perform the work which the client needs by making a plethora of calls to many different sub-system classes. They also know the sequence in which to call the methods and which methods to call in particular cases based on the particular situation. Saves the client from having to know the existence of the multitude of classes, how they work and the methods in them to be called.

Client - MiddleClass_GenX, Rich_BabyBoomer Relies on the functionality of the Facade to do all the little bits of work required and fit the pieces together on its behalf. Client will instantiate the Facade class, possibly pass a fairly simple parameter to it and sit back and let the Facade do the work, coordinate the results and return the results to it (the client).

Sample Code (Highlights)
Client
The facade simplifies the work of the client a lot. But if there are several facade classes, then you still need to decide which one to instantiate in the client.

Public Class MiddleClass_GenerationX
    Public Function GetVacation()     
        ' Makes use of the appropriate Facade class 
        Dim SpringBreakVacation As New FacadeA_AffordableVacationPlanner   
        ' Calls the main method of the Facade class to do all the nitty-gritty work 
        SpringBreakVacation.PlanAffordableVacation(AffordableVacationType.Adventurous)
    End Function
End Class


Facade Class
The facade takes care of a lot of method calls so the client's job is a lot easier.

Public Class FacadeA_AffordableVacationPlanner
    Public Function PlanAffordableVacation(ByVal TypeOfVacation As AffordableVacationType)
        ' First things first
        VisaRequirementsChecker.CheckVisaAdequacy()
        FlightBooker.BookCoachTickets()
        RentaCarBooker.BookRentaCar()
        If TypeOfVacation = AffordableVacationType.Adventurous Then
            ' Even Gen-Xers have to take time out to sleep, right?
            HotelBooker.BookBedandBreakFast()
            PartyBooker.BuyTickets()
        Else
            ' Have to have somewhere to sleep, right?
            HotelBooker.BookRegularHotel()
            SightSeeingBooker.BookSightSeeing()
' The middle aged folks tend to like cricket more, but I could be wrong !!!
            SportingEventBooker.BookICCWorldCupTickets()       
        End If
        ' With the money that's left over
        ' Jamaica is so beautiful that everyone has to see the sights !
        SightSeeingBooker.BookSightSeeing()    
        'And who would want to miss Reggae Sumfest !?!
        ReggaeConcertBooker.BookReggaeSumFestTickets()   
    End Function
End Class


Subsystem classes
Without the Facade classes, these are all the classes you would have to manage. Tedious !!!

http://www.programmersheaven.com/articles/designpatterns/image038.gif

Opportunities for and Costs of - Adaptation and Extension
Facade is a fairly simple pattern and so there is not much room for extension. The most obvious thing you can do is add more Facades to the system but in that way you are practically reworking the Facade. You could also possibly inherit from the Facade class and override methods. But the Facade is only supposed to have one or two methods to begin with, so by overriding a method or two, you still end up reworking the implementation.

I suppose you could put a lot of planning into the coding of your Facade and factor the Facade's main worker method (in our example, PlanAffordableVacation) into three or four method calls. You could then inherit from the Facade and override a method so that you book the ICC World Cup tickets and Reggae Sumfest tickets first. But the chances of coming across such a special requirements Facade are slim. Then again, you would have to know based on the specific situation you are coding for.

Making sure you get it right

Good Examples in Pattern Literature
[DOF 05]

Explanation Code


[LVS 03]

Explanation Code


Interface issues
None to speak of.

Namespace/Scope/Accessor issues
Just because we expect that the client will access the sub-system classes through the Facade doesn't mean that clients should not be free to access them directly. So there are no great scoping issues involved.

Common mistakes in Pattern Literature / Pitfalls to avoid
There isn't a lot to get wrong in this pattern and I have not seen many issues worth noting.

I imagine one temptation developers might have is to make all the sub-system classes private to clients and accessible only to facades. Remember though, that the pattern is supposed to provide a gentle-learning curve method of using sub-system functionality. It is not really supposed to hide sub-systems or make them inaccessible. So if you do choose to make the sub-systems inaccessible, then you should be doing it because of security issues you have, not so as to "implement the pattern properly", that is not the intent of the pattern.

Advanced Issues

Useful Variations
1a Parameterized facade

Activates relevant classes and methods within classes based on a parameter passed to it by the client. Parameters naturally incorporate any data or classes which may be passed to the Facade. A program to be compiled would be thought of in this sense as a parameter passed to a "Compiler Facade"

1b System-State-facade

The Facade activates classes and methods based on the external system state. Database optimizers which perform reading, writing and logging to a database and optimize their own performance based on memory and disk state would probably fit into this category.

2a Rote-Facade

Goes through the same sequence of steps no matter what, activating the same classes in the same sequence at all times.

2b Parameterized Facade

Activates relevant classes based on a parameter passed to it.

Advanced Discussion
I have seen references to the pattern as a non-pattern. I agree in a sense because there is nothing terribly special about it. There is no special interface to implement, there are no particular rules to get right. The Facade class doesn't have to hide the rest of the system, just broker the interactions generally. But it was generally still useful for the GoF to discuss it since it is a useful way of approaching issues and does make for some level of portability since the interaction with the sub-system classes is streamlined and made easier.

In a sense, most patterns more or less implement the Facade pattern as part of what they do, which is to hide the client-code from the internal complexity of a Containable-Object-Group.

The pattern does come with dangers and disadvantages we must bear in mind though. To some extent the Facade actually introduces some hard-wiring into a system. If we change the way some of the classes behind the facade work, then we invalidate all the clients which depend on it. So that even though the pattern recommends itself on the basis that sub-system classes need know nothing about it, certainly the programmers who maintain these subsystems need know about the facades which rely on them.

At the end of the day though, all the potentials pitfalls of the pattern seem to come down to communication. In motoring terms, when you change the course of the road, you have to introduce "Detour" signs. The use and maintenance of the classes within this pattern are no different.

Also, if you look at sports car 0-60 mph figures, you will notice one thing very consistent. The automatic version is always slower. The automatic transmission is another example of a facade system. You kick the gas pedal hard and depending on the speed your going and the current gear the car is in, the transmission changes down. Ease off the gas and the transmission changes to a higher gear. Contrast this with interacting with the tachometer, gas-pedal, gear-level and clutch and you will see that the gas-pedal is indeed a facade since it saves you from having to figure out which gear you should be in.

But serious drivers will tell you that an automatic transmission allows you less control over the vehicle since you can't predict exactly what gear the car is in. It's not as easy to gear down (unless you manually shift the lever) when doing wet roads, coming to a dramatic stop etc. Plus as said before, automatic cars are more lazy, use more gas and of course, if your battery dies, you can't push-start the car.

Now as described by the GoF, the Facade pattern does not prevent you from using all that latent power already written into the worker-classes. You can interact with them directly and unleash their power. But most programmers may fall into a rut and get so used to doing their work through the facade class that all the effort which went into writing the worker classes goes to waste, much the way that 80% of the features in Word and Excel are hardly used. It seems like a team-discipline / training / manual-reading issue, but its worth mentioning.

Explanation of Pattern subscripts
R Facade makes systems easy to use so that programmers who have just joined your team can make sense of and utilize complex-subsystems with minimal guidance. Be careful that this trivialization of complexity doesn't backfire though

P+ Following on the point above, experienced programmers can trace a path through a complex subsystem and record that knowledge in a Facade class

P- It could be that the particular situation that a programmer finds himself in requires the use of a high-performance class which is not available through the facade.

S+ You can implement need-to-know using Facade. In the scenario of vacation booking, without going through the Facade class, a dishonest programmer may bypass certain credit restrictions and book vacations without the proper credit checking.


About The Author David M. Simmonds and Bibliography


Downloads
Download design patterns sourcecodeDownload Sample sourcecode
Download design patterns sample databaseDownload Sample database
Download Sample design pattern UML diagramsDownload Sample UML diagrams




David M. Simmonds and Bibliography.about David M. Simmonds




 

Other Views

corner

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.