Facede Design Pattern in TypeScript (Part 1): Intent, Applicablility & Structure

Hooman Momtaheni
5 min readJun 16, 2024

--

Credit: wikipedia.com

In this series of articles, I intend to clarify the specific principles mentioned in the book “Design Patterns: Elements of Reusable Object-Oriented Software” about Facade design pattern. I tried to explain the difficult areas with examples from the TypeScript language.

Intent

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

Motivation

Structuring a system into subsystems helps reduce complexity. A common design goal is to minimize the communication and dependencies between the client and the subsystems. One way to achieve this goal is to introduce a facade object that provides a single, simplified interface to the more complex underlying facilities of a subsystem. Additionally, the facade can help manage interactions between multiple subsystems, further reducing the overall complexity and coupling within the system.

Credit: Design Patterns: Elements of Reusable Object-Oriented Software

Consider for example a programming environment* that gives applications access to its compiler subsystem. This subsystem contains classes such as Scanner, Parser, ProgramNode, BytecodeStream, and ProgramNodeBuilder that implement the compiler. Some specialized applications might need to access these classes directly. But most clients of a compiler generally don’t care about details like parsing and code generation; they merely want to compile some code. For them, the powerful but low-level interfaces in the compiler subsystem only complicate their task.

To provide a higher-level interface that can shield clients from these classes, the compiler subsystem also includes a Compiler class. This class defines a unified interface to the compiler’s functionality. The Compiler class acts as a facade: It offers clients a single, simple interface to the compiler subsystem. It glues together the classes that implement compiler functionality without hiding them completely. The compiler facade makes life easier for most programmers without hiding the lower-level functionality from the few that need it.

Credit: Design Patterns: Elements of Reusable Object-Oriented Software

A simple example in TS:

class Scanner {
scan(sourceCode: string): string {
console.log("Scanning source code...");
return "tokens"; // Simulated tokens
}
}

class Parser {
parse(tokens: string): string {
console.log("Parsing tokens...");
return "abstractSyntaxTree"; // Simulated AST
}
}

class ProgramNode {
constructor(private ast: string) {}

traverse() {
console.log("Traversing the AST...");
}
}

class BytecodeStream {
constructor() {}

generateBytecode(): string {
console.log("Generating bytecode...");
return "bytecode"; // Simulated bytecode
}
}

class ProgramNodeBuilder {
build(ast: string): ProgramNode {
console.log("Building program node...");
return new ProgramNode(ast);
}
}

class Compiler {
private scanner: Scanner;
private parser: Parser;
private nodeBuilder: ProgramNodeBuilder;
private bytecodeStream: BytecodeStream;

constructor() {
this.scanner = new Scanner();
this.parser = new Parser();
this.nodeBuilder = new ProgramNodeBuilder();
this.bytecodeStream = new BytecodeStream();
}

compile(sourceCode: string): string {
const tokens = this.scanner.scan(sourceCode);
const ast = this.parser.parse(tokens);
const programNode = this.nodeBuilder.build(ast);
programNode.traverse();
return this.bytecodeStream.generateBytecode();
}
}

const compiler = new Compiler();
const sourceCode = "console.log('Hello, World!');";
const bytecode = compiler.compile(sourceCode);

console.log("Compiled bytecode:", bytecode);

Applicability

Use the Facade pattern when:

· you want to provide a simple interface to a complex subsystem. Subsystems often get more complex as they evolve. Most patterns, when applied, result in more and smaller classes. This makes the subsystem more reusable and easier to customize, but it also becomes harder to use for clients that don’t need to customize it. A facade can provide a simple default view of the subsystem that is good enough for most clients. Only clients needing more customizability will need to look beyond the facade.

· you want to layer your subsystems. Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them communicate with each other solely through their facades.

· There are many dependencies between clients and the implementation classes of an abstraction. Introduce a facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability.

let’s explain this concept with example:

Consider we have a complex system involving a subsystem for order processing (The abstraction) in an e-commerce application. The subsystem includes classes for inventory management, payment processing, and shipping (The implementation classes of an abstraction). We will use the Facade pattern to simplify the interaction with this subsystem.

Subsystem Classes

class InventoryManager {
checkInventory(productId: string): boolean {
console.log(`Checking inventory for product ${productId}`);
// Simulated inventory check
return true;
}

reserveProduct(productId: string) {
console.log(`Reserving product ${productId}`);
}
}

class PaymentProcessor {
processPayment(amount: number): boolean {
console.log(`Processing payment of $${amount}`);
// Simulated payment processing
return true;
}
}

class ShippingManager {
arrangeShipping(productId: string) {
console.log(`Arranging shipping for product ${productId}`);
}
}

Facade Class

class OrderFacade {
private inventoryManager: InventoryManager;
private paymentProcessor: PaymentProcessor;
private shippingManager: ShippingManager;

constructor() {
this.inventoryManager = new InventoryManager();
this.paymentProcessor = new PaymentProcessor();
this.shippingManager = new ShippingManager();
}

placeOrder(productId: string, amount: number) {
if (this.inventoryManager.checkInventory(productId)) {
this.inventoryManager.reserveProduct(productId);
if (this.paymentProcessor.processPayment(amount)) {
this.shippingManager.arrangeShipping(productId);
console.log('Order placed successfully!');
} else {
console.log('Payment failed. Order not placed.');
}
} else {
console.log('Product not available in inventory. Order not placed.');
}
}
}

Client Code

const orderFacade = new OrderFacade();
orderFacade.placeOrder('1234', 99.99);

By using Facade we simplified client interaction with subsystem, decoupling client from the subsystem implementation details and also gain subsystem independence and portability.

Structure

Credit: Design Patterns: Elements of Reusable Object-Oriented Software

Participants

· Facade (Compiler)

- knows which subsystem classes are responsible for a request.

- delegates client requests to appropriate subsystem objects.

· Subsystem classes (Scanner, Parser, ProgramNode, etc.)

- implement subsystem functionality.

- handle work assigned by the Facade object.

  • have no knowledge of the facade; that is, they keep no references to it.

Collaborations

· Clients communicate with the subsystem by sending requests to Facade, which forwards them to the appropriate subsystem object(s). Although the subsystem objects perform the actual work, the facade may have to do work of its own to translate its interface to subsystem interfaces.

· Clients that use the facade don’t have to access its subsystem objects directly.

In the next part we will discuss about consequences and related pattern of Facade design pattern.

--

--

Hooman Momtaheni

Full Stack Web Application Developer | Admire foundations and structures | Helping companies have reliable web apps and motivated software development team