Facade Pattern
The Facade pattern provides a simplified interface to a complex subsystem. It reduces the complexity of the system by hiding the underlying implementation details.
When to Use:
Use the Facade pattern when you want to simplify the interface to a complex system.
Example
// Subsystem classesclass CPU { freeze() { console.log('CPU freezing...'); } jump(position: number) { console.log(`CPU jumping to position ${position}`); } execute() { console.log('CPU executing...'); }}
class Memory { load(position: number, data: string) { console.log(`Memory loading data at position ${position}`); }}
class HardDrive { read(lba: number, size: number) { return 'Some data from HardDrive'; }}
// Facade classclass ComputerFacade { private cpu: CPU; private memory: Memory; private hardDrive: HardDrive;
constructor() { this.cpu = new CPU(); this.memory = new Memory(); this.hardDrive = new HardDrive(); }
start() { this.cpu.freeze(); this.memory.load(0, this.hardDrive.read(0, 4096)); this.cpu.jump(0); this.cpu.execute(); }}
// Usageconst computer = new ComputerFacade();computer.start();
Pros:
- Simplifies the interface to complex subsystems.
- Promotes loose coupling between clients and subsystems.
Cons:
- Can lead to the creation of overly simple interfaces that don’t offer enough flexibility.
- May increase the complexity of the system if not used judiciously.