Rusty Divine

Live, Love, Learn, Teach

Learning Design Patterns – Facade Pattern

This week I'll be simplifying my life with the Facade Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The Facade Pattern simplifies a complex interface so that it's client can rely on simple methods in the facade that handle multi-step calls to subclasses. The client might call facade.PowerUp, then the facade would turn on all of the subcomponents in the correct order and adjust their initial properties.

Where is it used?
The Facade Pattern is used to simplify processes that rely on multiple objects to complete, and to simplify frameworks (or even individual classes) that have an overwhelming number of interface methods.

The pattern is also used to adhere to the Principle of Least Knowledge, an OO design principle also known as the Law of Demeter. The principle recommends that a class should not talk to anyone except its close friends, who are:

  • Itself
  • Someone passed in as a parameter
  • Anyone who it instantiates
  • Anyone who is in it's instance variable list

In other words, don't instantiate an object (new Friend), return another object (Friend.Friend), and call the second friend's method (Friend.Friend.ComePlay).

But why?
Besides simplifying a complex interface and promoting good design through the Principle of Least Knowledge, the pattern also helps the design of an application by decoupling the client from all of the subclasses - if a subclass method changes, then the update is made in the facade without affecting the client code.

OK, and how is it implemented?


public class SecurityLockFacade {
	//indicates pass or fail
	VerificationLight light;
	VerificationBeeper beeper;
	Door door;
	public SecurityLock (Door door){
		//initialize light, etc.
		this.door = door;

	public boolean open(Badge badge) {
		boolean authorized = door.authorized(badge);

		if (authorized) {;;
			return true;
		} else {;
			return false;

// Create a client that doesn't need to know about all 
// the beeping and lights, just calls open
public class TestDoor {

	public static void main(Door door, Badge badge) {
		SecurityLockFacade securityLock = 
		  new SecurityLockFacade(door);

		if ( {
			//walk in
		} else	{
			//FBI has been alerted; run away!
blog comments powered by Disqus