#
Facade
This tutorial explains to you the design pattern named Facade (which is a Structural Pattern).
#
Facade Pattern - theory
Supposing, we have same classes under one or more interfaces, and we want to create a class to be used for calling methods
from these classes. That kind of situation is explained by the Facade
Design Pattern. Facade Design Pattern in
Java is used when we want to create a class and call methods from other classes.
In Facade Design Pattern, the main idea is to have one point from calling many methods created in more classes.
Take a look at the following UML diagram representing the Facade design pattern (for my example):
#
Facade Pattern - example
Here is that example using the Facade Design Pattern in Java:
package facade.java.example;
public interface Car {
// This method build a car.
public void build();
}
package facade.java.example;
public class BMW implements Car{
public void build(){
System.out.println("A BMW car has been built.");
}
}
package facade.java.example;
public class Chevrolet implements Car{
public void build(){
System.out.println("A Chevrolet car has been built.");
}
}
package facade.java.example;
public class Renault implements Car{
public void build(){
System.out.println("A Renault car has been built.");
}
}
package facade.java.example;
public class FacadeForCar {
private Car bmw;
private Car chevrolet;
private Car renault;
public FacadeForCar(){
this.bmw = new BMW();
this.chevrolet = new Chevrolet();
this.renault = new Renault();
}
public void buildBmw(){
bmw.build();
}
public void buildChevrolet(){
chevrolet.build();
}
public void buildRenault(){
renault.build();
}
}
package facade.java.example;
public class FacadeJavaPatternExampleMain {
public static void main(String[] args) {
FacadeForCar facadeForCar = new FacadeForCar();
facadeForCar.buildBmw();
facadeForCar.buildChevrolet();
facadeForCar.buildRenault();
}
}
When you run this example you will receive the following result: