Facade

Introduction

When you design a system into subsystems to reduce complexity, you want to minimize the communication and dependencies between the subsystems. You may want to have a single simplified interface to help to achieve this. Here comes the Facade pattern.

Definition

Provide a unified interface to a set of interfaces of subsystems. Facade defines a higher-level interface that makes the subsystems easier to use.

Diagram

Facade

Participants

  • Facade
    • knows which subsystem classes are responsible for a request.
    • delegates client request to appropriate subsystem objects.
  • subsystem classes
    • implememt subsystem functionality.
    • handle work assigned by the Facade object.
    • have no knowledge of facade, that is, they keep no references to it.

Example

// Facade
public class Computer {
	private CPU cpu;
	private Memory memory;
	private Disk disk;
	
	public Computer() {
		cpu = new CPU();
		memory = new Memory();
		disk = new Disk();
	}
	
	public void startup() {
		cpu.startup();
		memory.startup();
		disk.startup();
	}
	
	public void shutdown() {
		disk.shutdown();
		memory.shutdown();
		cpu.shutdown();
	}
	
}

// subsystems
public class CPU {
	public void startup() {
		System.out.println("cpu startup.");
	}
	public void shutdown() {
		System.out.println("cpu shutdown");
	}
}

public class Disk {
	public void startup() {
		System.out.println("disk startup.");
	}
	public void shutdown() {
		System.out.println("disk shutdown.");
	}
}

public class Memory {
	public void startup() {
		System.out.println("memory startup.");
	}
	public void shutdown() {
		System.out.println("memory shutdown.");
	}
}

// Client
public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Computer computer = new Computer();
		
		System.out.println("Startup the computer.");
		computer.startup();
		System.out.println("The computer is running.");
		
		System.out.println("---------------");
		System.out.println("Shutdown the computer.");
		computer.shutdown();
		System.out.println("The computer is poweroff");
	}

}

Output:

Startup the computer.
cpu startup.
memory startup.
disk startup.
The computer is running.
---------------
Shutdown the computer.
disk shutdown.
memory shutdown.
cpu shutdown
The computer is poweroff

As the code shows, the subsystems: CPU, Disk and Memory don’t know whether there is a facade object or not. The facade object supplies a new interface and delegates the request to subsystems. In someway, it seems that Facade encapsulates the subsystems’ interface in higher level.

Usage

  • When you want to provide a simple interface to a complex subsystem.
  • When there are many dependencies between clients and the implementation classes of an abstraction.
  • When you want to layer your subsystems.

See Also

blog comments powered by Disqus