Facade Pattern

Facade Pattern

The Facade pattern is a structural design pattern that provides a simplified interface to a complex subsystem. It is especially useful when you need to interact with multiple interdependent classes in a system and want to provide a more user-friendly interface.

What You Will Learn

In this lesson, you will master:

  • The core concept of the Facade pattern.
  • How to implement the Facade pattern using a real-world example of a computer system with subsystems like the CPU, Memory, and HardDrive.
  • The significance and benefits of using the Facade pattern in software development.

Let's dive into the Facade pattern through a practical example.

Implementing the Facade Pattern

In our example, we'll create a ComputerFacade class that interacts with the CPU, Memory, and HardDrive classes to provide a simple interface for starting and shutting down a computer.

Step 1: Define Subsystem Classes

First, we define the subsystems CPU, Memory, and HardDrive, each responsible for its specific operations.

CPU class:

public class CPU {
    public void freeze() {
        System.out.println("CPU freezing...");
    }

    public void jump(long position) {
        System.out.println("CPU jumping to position " + position);
    }

    public void execute() {
        System.out.println("CPU executing...");
    }

    public void shutdown() {
        System.out.println("CPU shutting down...");
    }
}

In this class, the CPU handles operations like freezing, jumping to a position, executing instructions, and shutting down.

Memory class:

public class Memory {
    public void load(long position, String data) {
        System.out.println("Memory loading " + data + " at position " + position);
    }

    public void clear() {
        System.out.println("Memory clearing data...");
    }
}

Here, the Memory class is responsible for loading data into memory and clearing it when necessary.

HardDrive class:

public class HardDrive {
    public String read(long lba, int size) {
        return "Data from sector " + lba + " with size " + size;
    }

    public void stop() {
        System.out.println("Hard Drive stopping...");
    }
}

The HardDrive class handles reading data from specified sectors and stopping the hard drive.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal