The Facade Pattern in Java

Introduction to the Facade Pattern

Design pattern in a simple meaning, is a way to design reusable object-oriented code. We can think of ways to design our classes, interfaces, enums and their members so that the code is reusable but flexible.

There are 23 most important design patterns, pioneered by the book Design Patterns: Elements of Reusable Object-Oriented Software, written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides or Gang of Four for short. We will cover these design pattern one by one.

The Facade pattern provides a unified interface to a set of interfaces.

Implementation of Facade Pattern in Java

This pattern is rather straightforward, we will make an abstract class Animal in the src folder:

public abstract class Animal {
  abstract void makeSound();
}

Now in the src folder we create four classes. The Cat class:

public class Cat extends Animal{
  void makeSound() {
    System.out.println("meow");
  }
}

The Dog class:

public class Dog extends Animal{
  void makeSound() {
    System.out.println("growl");
  }
}

The Duck class:

public class Duck extends Animal{
  void makeSound() {
    System.out.println("quack");
  }
}

The Sheep class:

public class Sheep extends Animal{
  void makeSound() {
    System.out.println("baa");
  }
}

And the Facade class:

public class Facade {
  private final Animal dog, cat, duck, sheep;
  Facade(){
    dog = new Dog();
    cat = new Cat();
    duck = new Duck();
    sheep = new Sheep();
  }
  void catSound(){
    cat.makeSound();
  }
  void dogSound(){
    dog.makeSound();
  }
  void duckSound(){
    duck.makeSound();
  }
  void sheepSound(){
    sheep.makeSound();
  }
}

The class Facade is a unified class of four classes Cat, Dog, Duck, Sheep. The callers of Facade class don’t even know that those four classes existed. They just know the Facade class and four methods that the Facade provides. Next in Test.java:

public class Test {
  public static void main(String[] args){
    Facade facade = new Facade();
    facade.catSound();
    facade.dogSound();
    facade.duckSound();
    facade.sheepSound();
  }
}

Run the code and we have:

meow
growl
quack
baa

 

 

Leave a Reply