DEV Community

Tu Bui
Tu Bui

Posted on

Facade Pattern

https://refactoring.guru/design-patterns/facade

Target: Avoid call many function from something or package.
A facade is a class that provides a simple interface to a complex subsystem which contains lots of moving parts. A facade might provide limited functionality in comparison to working with the subsystem directly. However, it includes only those features that clients really care about.

Example:
When you want to order pizza. Just call to the operator who provide you all function of shop like order, payment, delivery,...

interface IGameFacade {
    startGame(): void;
    pauseGame(): void;
    endGame(): void;
}

class GameFacade implements IGameFacade {
    private physicsSystem: PhysicsSystem;
    private uiManager: UIManager;

    constructor() {
        this.physicsSystem = new PhysicsSystem();
        this.uiManager = new UIManager();
    }

    startGame() {
        this.physicsSystem.enable();
        this.uiManager.showGameUI();
        console.log("Game started!");
    }

    pauseGame() {
        this.physicsSystem.disable();
        this.uiManager.showPauseMenu();
        console.log("Game paused.");
    }

    endGame() {
        this.physicsSystem.reset();
        this.uiManager.showEndScreen();
        console.log("Game ended.");
    }
}

class PhysicsSystem {
    enable() { console.log("Physics enabled"); }
    disable() { console.log("Physics disabled"); }
    reset() { console.log("Physics reset"); }
}

class UIManager {
    showGameUI() { console.log("Game UI shown"); }
    showPauseMenu() { console.log("Pause menu shown"); }
    showEndScreen() { console.log("End screen shown"); }
}

// Usage
const game = new GameFacade();
game.startGame();
game.pauseGame();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)