Skip to main content

🧩 Facade Pattern

βœ… Intent​

  • Provide a simple, unified interface to a complex subsystem
  • Hide internal logic behind a clean and task-oriented entry point

βœ… Motivation​

  • Simplify client responsibilities by exposing only what’s necessary
  • Help decouple client code from subsystem changes

βœ… When to Use​

  • When a task involves multiple steps across services
  • To provide a gateway for frameworks or module groups
  • To simplify complex workflows for reuse and clarity

βœ… Code Example​

class AuthService {
authenticate(userId: string): boolean {
console.log(`ユーアーθͺθ¨Ό: ${userId}`);
return true;
}
}

class UserProfileService {
load(userId: string): object {
console.log(`プロフィール取得: ${userId}`);
return { name: "Hiroshi", id: userId };
}
}

class AuditService {
log(action: string) {
console.log(`[η›£ζŸ»γƒ­γ‚°] ${action}`);
}
}

// Facade
class UserProfileFacade {
private auth = new AuthService();
private profile = new UserProfileService();
private audit = new AuditService();

show(userId: string) {
if (this.auth.authenticate(userId)) {
const profile = this.profile.load(userId);
console.log(profile);
this.audit.log("プロフィール葨瀺");
}
}
}

// εˆ©η”¨δΎ‹
const facade = new UserProfileFacade();
facade.show("user-123");

βœ… Explanation​

This example applies the Facade pattern to unify three distinct subsystems β€” AuthService, UserProfileService, and AuditService β€” under a simple interface.

The UserProfileFacade class consolidates these into a single show(userId) call that handles authentication, profile retrieval, and audit logging.

1. Facade Pattern Overview​

  • Subsystem Classes: Provide individual pieces of logic

    • In this example: AuthService, UserProfileService, AuditService
  • Facade: Simplifies access to the subsystems through a unified interface

    • Here: UserProfileFacade
  • Client: Uses the facade to complete a complex task via a single call

    • Here: facade.show("user-123")

2. Key Classes and Roles​

  • AuthService

    • Authenticates the user
  • UserProfileService

    • Fetches user profile information
  • AuditService

    • Logs the profile access action
  • UserProfileFacade

    • Encapsulates the entire workflow into a single show() method
  • Client Code

    • Calls only UserProfileFacade.show() instead of dealing with each subsystem separately

3. UML Class Diagram​

4. Benefits of the Facade Pattern​

  • Simplified Interface: Reduces the learning curve and usage complexity
  • Decoupling: Hides internal subsystem logic from the client
  • Improved Maintainability: Internal changes are absorbed by the facade, not the client

This design is especially helpful when internal complexity needs to be hidden to promote reuse and cleaner interfaces.
It enhances both usability and maintainability by preventing business logic from leaking into calling code.