patterntypescriptTip
Facade Pattern: Simplify Complex Subsystem Interaction
Viewed 0 times
facade patternstructural patternsubsystemsimplify interfaceorchestrationhigh level api
Problem
Client code must coordinate multiple subsystem classes in a specific sequence to accomplish a common task. This spreads orchestration logic across call sites and ties clients to implementation details.
Solution
Create a facade class that exposes a simple, high-level interface and hides the orchestration of subsystem calls.
// Complex subsystems
class VideoDecoder { decode(file: string) { return `decoded:${file}`; } }
class AudioMixer { mix(audio: string) { return `mixed:${audio}`; } }
class VideoEncoder { encode(video: string, audio: string) { return `final.mp4`; } }
class FileWriter { save(data: string, path: string) { console.log(`saved ${data} to ${path}`); } }
// Facade
class VideoConversionFacade {
private decoder = new VideoDecoder();
private mixer = new AudioMixer();
private encoder = new VideoEncoder();
private writer = new FileWriter();
convert(inputFile: string, outputPath: string): void {
const video = this.decoder.decode(inputFile);
const audio = this.mixer.mix(inputFile);
const result = this.encoder.encode(video, audio);
this.writer.save(result, outputPath);
}
}
// Client only needs the facade
const converter = new VideoConversionFacade();
converter.convert('input.avi', '/output/result.mp4');Why
Facades reduce coupling between clients and complex subsystems. The subsystem can evolve internally without affecting clients as long as the facade contract is preserved.
Gotchas
- A facade should not prevent access to the subsystem when clients need fine-grained control — keep the subsystem classes accessible.
- Facades can become god objects if too much logic migrates into them. They should orchestrate, not implement business logic.
- Multiple facades can coexist for different use cases against the same subsystem.
Revisions (0)
No revisions yet.