Facade Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the facade pattern, a structural design pattern.
Tutorial created using: Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)


Page:    1 2 >

The facade pattern is a structural design pattern. In the facade pattern, a facade classes is used to provide a single interface to set of classes. The facade simplifies a clients interaction with a complex system by localizing the interactions into a single interface. As a result, the client can interact with a single object rather than being required to interact directly in complicated ways with the objects that make up the subsystem.

As an example, supposed we have three horribly written classes. For based on the class and method names (and the lack of documentation), it would be very difficult for a client to interact with these classes.

Class1's doSomethingComplicated() method takes an integer and returns its cube.

Class1.java

package com.cakes;

public class Class1 {

	public int doSomethingComplicated(int x) {
		return x * x * x;
	}

}

Class2's doAnotherThing() method doubles the cube of an integer and returns it.

Class2.java

package com.cakes;

public class Class2 {

	public int doAnotherThing(Class1 class1, int x) {
		return 2 * class1.doSomethingComplicated(x);
	}
}

Class3's doMoreStuff() takes a Class1 object, a Class2 object, and an integer and returns twice the sixth power of the integer.

Class3.java

package com.cakes;

public class Class3 {

	public int doMoreStuff(Class1 class1, Class2 class2, int x) {
		return class1.doSomethingComplicated(x) * class2.doAnotherThing(class1, x);
	}

}

For a client unfamiliar with Class1, Class2, and Class3, it would be very difficult to figure out how to interact with these classes. The classes interact and perform tasks in unclear ways. As a result, we need to be able to simplify interaction with this system of classes so that clients can interact with these classes in a simple, standardized manner.

We do this with the Facade class. The Facade class has three methods: cubeX(), cubeXTimes2(), and xToSixthPowerTimes2(). The names of these methods clearly indicate what they do, and these methods hide the interactions of Class1, Class2, and Class3 from client code.

Facade.java

package com.cakes;

public class Facade {

	public int cubeX(int x) {
		Class1 class1 = new Class1();
		return class1.doSomethingComplicated(x);
	}

	public int cubeXTimes2(int x) {
		Class1 class1 = new Class1();
		Class2 class2 = new Class2();
		return class2.doAnotherThing(class1, x);
	}

	public int xToSixthPowerTimes2(int x) {
		Class1 class1 = new Class1();
		Class2 class2 = new Class2();
		Class3 class3 = new Class3();
		return class3.doMoreStuff(class1, class2, x);
	}

}

(Continued on page 2)

Page:    1 2 >


Related Tutorials: