Facade Pattern

Facade Pattern is a structural design pattern that hides the complexibilities of the system and provides interface to the client using which the client can access the system. This pattern involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes.

In the following example there is a Shape interface and concrete classes implementing the Shape interface. Class ShapeMaker acts as a facade. ShapeMaker class uses the concrete classes to delegate user calls to these classes.

Facade Pattern UML Diagram

Step 1 : Create an interface

public interface Shape {
void draw();
}

Step 2 : Create concrete classes implementing the same interface

public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle::draw()");
}
}

public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}

public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square::draw()");
}
}

Step 3 : Create a facade class

public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;

public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}

public void drawCircle(){
circle.draw();
}
public void drawRectangle(){
rectangle.draw();
}
public void drawSquare(){
square.draw();
}
}

Step 4 : Use the facade to draw various types of shapes

public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();

shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}

The output will be :

Circle::draw()
Rectangle::draw()
Square::draw()

Leave a Reply

Your email address will not be published. Required fields are marked *