opencodez

Java Structural Design Patterns – Facade Pattern

Facade Pattern provides the ease of usability for a system by hiding its complexity. It comes under a Structural design pattern. In this pattern client code can access the system but it hides the working of the system by providing a simpler interface to use for client. In this pattern one class gets created (FACADE) which includes user defined functions and delegates providing calls to the classes belongs to the system. Now the client code interacts only with Facade, not with the actual system.

If your solution or project has below concerns you can consider using Facade Pattern:

xHere are ALL other Java Design Patterns, explained in detail with examplesx

Facade Pattern by Example

We will understand this pattern using the simple concept of an Animal speaking. We will define an interface and a couple of animals will implement it.

public interface Animal {
	public void speak();
}

Concrete Animal Classes

public class Dog implements Animal {

	@Override
	public void speak() {
		System.out.println("Dog Speaks :: Bow!! Bow!!");
	}

}

one more

public class Cat implements Animal {

	@Override
	public void speak() {
		System.out.println("Cat Speaks :: Meow!! Meow!!");
	}

}

Let us add the facade and supporting methods

public class AnimalFacade {
	
	private Animal dog;
	private Animal cat;
	
	public AnimalFacade() {
		dog = new Dog();
		cat = new Cat();
	}
	
	public void speakDog() {
		dog.speak();
	}
	
	public void speakCat() {
		cat.speak();
	}

}

Running the Example

public class FacadeDemo {

	public static void main(String[] args) {
		
		AnimalFacade af = new AnimalFacade();
		af.speakDog();
		af.speakCat();
		
	}
}

Output

Dog Speaks :: Bow!! Bow!!
Cat Speaks :: Meow!! Meow!!

Conclusion

Facade pattern does beautiful work by hiding all the complexities of your system and provides a simpler interface API to use. You can use this patterns if an entry point is needed to each level of layered software, or
the abstractions and implementations of a subsystem are tightly coupled.

The source code is available in our Github repository.

Download Code

x

xHere are ALL other Java Design Patterns, explained in detail with examplesx