Polski

Article · Facade · Adapter

Facade – one simple entry point to a complex subsystem

Facade exposes one convenient operation that coordinates many subsystem classes behind the scenes. An example of course enrollment with payment, access and a welcome email in C#, TypeScript, Java, Go and Python.

By · · 11 min read

To enroll a student in a course, you have to find or create an account, take the payment, grant access to the materials and send a welcome email – in that order, with error handling in between. Facade wraps that choreography in a single enroll() method, so the controller, the batch job and the admin panel do not have to know four classes and how they depend on each other.

4
subsystem classes – accounts, billing, access, mail
1
call for the client – enroll(email, course, price)
0
changes to the subsystem – the facade only coordinates it

The problem: every client knows the whole choreography

The course platform has three places where a student gets enrolled: a purchase on the website, an import of participants from a company, and manual addition by an administrator. Each of them looks more or less like this:

checkout-controller.ts
const userId = accounts.findOrCreate(email);
const paymentId = billing.charge(userId, price);
try {
  access.grant(userId, courseId);
} catch (e) {
  billing.refund(paymentId); // someone forgot this in the admin panel
  throw e;
}
mailer.sendWelcome(email, courseId);

The code is copied three times and slightly different in each place. In the admin panel someone forgot to refund the payment when granting access fails, and the company import does not send emails. When a new step arrives – say, adding the student to a community channel – every copy has to be found and fixed.

The solution: one class that knows the order

We create an EnrollmentFacade with one method, enroll(email, courseId, priceCents). The facade receives the subsystem classes in its constructor and calls them in the right order, including compensation (refunding the payment) when something goes wrong. All three clients call only the facade.

Diagram: Clients talk to the facade; the subsystem stays available for special cases
Diagram: What happens inside enroll()
RoleIn the exampleResponsibility
FacadeEnrollmentFacadeknows the order of steps and delegates to the subsystem
Subsystem classesAccounts, Billing, CourseAccess, Mailerthe actual work; they know nothing about the facade
Clientspurchase controller, import, admin paneluse one high-level operation

Implementation in five languages

The subsystem classes are deliberately simplified here – in a real system they are separate modules, often with their own databases or external APIs. What matters is what the facade does: it sets the order, handles compensation and returns a single, understandable result to the client.

EnrollmentFacade

Enrollment.cs
var enrollment = new EnrollmentFacade(new Accounts(), new Billing(), new CourseAccess(), new Mailer());
Console.WriteLine(enrollment.Enroll("ola@example.com", "design-patterns", priceCents: 19900));

// Subsystem classes: each is fine on its own, but callers must use them in the right order.
public sealed class Accounts
{
    public string FindOrCreate(string email) => $"user:{email}";
}

public sealed class Billing
{
    public string Charge(string userId, long amountCents) => $"pay_{amountCents}";
    public void Refund(string paymentId) => Console.WriteLine($"refunded {paymentId}");
}

public sealed class CourseAccess
{
    public void Grant(string userId, string courseId) => Console.WriteLine($"access: {userId} -> {courseId}");
}

public sealed class Mailer
{
    public void SendWelcome(string email, string courseId) => Console.WriteLine($"mail to {email}: {courseId}");
}

// Facade: one simple operation that hides the orchestration.
public sealed class EnrollmentFacade(Accounts accounts, Billing billing, CourseAccess access, Mailer mailer)
{
    public string Enroll(string email, string courseId, long priceCents)
    {
        var userId = accounts.FindOrCreate(email);
        var paymentId = billing.Charge(userId, priceCents);
        try
        {
            access.Grant(userId, courseId);
        }
        catch
        {
            billing.Refund(paymentId); // keep the subsystems consistent
            throw;
        }
        mailer.SendWelcome(email, courseId);
        return $"enrolled {userId} in {courseId} ({paymentId})";
    }
}
enrollment.ts
// Subsystem classes: each is fine on its own, but callers must use them in the right order.
class Accounts {
  findOrCreate(email: string): string {
    return `user:${email}`;
  }
}

class Billing {
  charge(userId: string, amountCents: number): string {
    return `pay_${amountCents}`;
  }
  refund(paymentId: string): void {
    console.log(`refunded ${paymentId}`);
  }
}

class CourseAccess {
  grant(userId: string, courseId: string): void {
    console.log(`access: ${userId} -> ${courseId}`);
  }
}

class Mailer {
  sendWelcome(email: string, courseId: string): void {
    console.log(`mail to ${email}: ${courseId}`);
  }
}

// Facade: one simple operation that hides the orchestration.
class EnrollmentFacade {
  constructor(
    private readonly accounts = new Accounts(),
    private readonly billing = new Billing(),
    private readonly access = new CourseAccess(),
    private readonly mailer = new Mailer(),
  ) {}

  enroll(email: string, courseId: string, priceCents: number): string {
    const userId = this.accounts.findOrCreate(email);
    const paymentId = this.billing.charge(userId, priceCents);
    try {
      this.access.grant(userId, courseId);
    } catch (err) {
      this.billing.refund(paymentId); // keep the subsystems consistent
      throw err;
    }
    this.mailer.sendWelcome(email, courseId);
    return `enrolled ${userId} in ${courseId} (${paymentId})`;
  }
}

console.log(new EnrollmentFacade().enroll("ola@example.com", "design-patterns", 19900));
Enrollment.java
// Subsystem classes: each is fine on its own, but callers must use them in the right order.
class Accounts {
    String findOrCreate(String email) { return "user:" + email; }
}

class Billing {
    String charge(String userId, long amountCents) { return "pay_" + amountCents; }
    void refund(String paymentId) { System.out.println("refunded " + paymentId); }
}

class CourseAccess {
    void grant(String userId, String courseId) { System.out.println("access: " + userId + " -> " + courseId); }
}

class Mailer {
    void sendWelcome(String email, String courseId) { System.out.println("mail to " + email + ": " + courseId); }
}

// Facade: one simple operation that hides the orchestration.
final class EnrollmentFacade {
    private final Accounts accounts;
    private final Billing billing;
    private final CourseAccess access;
    private final Mailer mailer;

    EnrollmentFacade(Accounts accounts, Billing billing, CourseAccess access, Mailer mailer) {
        this.accounts = accounts;
        this.billing = billing;
        this.access = access;
        this.mailer = mailer;
    }

    String enroll(String email, String courseId, long priceCents) {
        String userId = accounts.findOrCreate(email);
        String paymentId = billing.charge(userId, priceCents);
        try {
            access.grant(userId, courseId);
        } catch (RuntimeException e) {
            billing.refund(paymentId); // keep the subsystems consistent
            throw e;
        }
        mailer.sendWelcome(email, courseId);
        return "enrolled " + userId + " in " + courseId + " (" + paymentId + ")";
    }
}

public class Enrollment {
    public static void main(String[] args) {
        var facade = new EnrollmentFacade(new Accounts(), new Billing(), new CourseAccess(), new Mailer());
        System.out.println(facade.enroll("ola@example.com", "design-patterns", 19_900));
    }
}
enrollment.go
package main

import "fmt"

// Subsystem types: each is fine on its own, but callers must use them in the right order.
type Accounts struct{}

func (Accounts) FindOrCreate(email string) string { return "user:" + email }

type Billing struct{}

func (Billing) Charge(userID string, cents int64) (string, error) {
	return fmt.Sprintf("pay_%d", cents), nil
}

func (Billing) Refund(paymentID string) { fmt.Println("refunded", paymentID) }

type CourseAccess struct{}

func (CourseAccess) Grant(userID, courseID string) error {
	fmt.Println("access:", userID, "->", courseID)
	return nil
}

type Mailer struct{}

func (Mailer) SendWelcome(email, courseID string) { fmt.Println("mail to", email+":", courseID) }

// EnrollmentFacade offers one simple operation that hides the orchestration.
type EnrollmentFacade struct {
	Accounts Accounts
	Billing  Billing
	Access   CourseAccess
	Mailer   Mailer
}

func (f EnrollmentFacade) Enroll(email, courseID string, priceCents int64) (string, error) {
	userID := f.Accounts.FindOrCreate(email)
	paymentID, err := f.Billing.Charge(userID, priceCents)
	if err != nil {
		return "", fmt.Errorf("charge: %w", err)
	}
	if err := f.Access.Grant(userID, courseID); err != nil {
		f.Billing.Refund(paymentID) // keep the subsystems consistent
		return "", fmt.Errorf("grant access: %w", err)
	}
	f.Mailer.SendWelcome(email, courseID)
	return fmt.Sprintf("enrolled %s in %s (%s)", userID, courseID, paymentID), nil
}

func main() {
	fmt.Println(EnrollmentFacade{}.Enroll("ola@example.com", "design-patterns", 19900))
}
enrollment.py
# Subsystem classes: each is fine on its own, but callers must use them in the right order.
class Accounts:
    def find_or_create(self, email: str) -> str:
        return f"user:{email}"


class Billing:
    def charge(self, user_id: str, amount_cents: int) -> str:
        return f"pay_{amount_cents}"

    def refund(self, payment_id: str) -> None:
        print(f"refunded {payment_id}")


class CourseAccess:
    def grant(self, user_id: str, course_id: str) -> None:
        print(f"access: {user_id} -> {course_id}")


class Mailer:
    def send_welcome(self, email: str, course_id: str) -> None:
        print(f"mail to {email}: {course_id}")


class EnrollmentFacade:
    """One simple operation that hides the orchestration."""

    def __init__(self, accounts: Accounts, billing: Billing, access: CourseAccess, mailer: Mailer) -> None:
        self._accounts = accounts
        self._billing = billing
        self._access = access
        self._mailer = mailer

    def enroll(self, email: str, course_id: str, price_cents: int) -> str:
        user_id = self._accounts.find_or_create(email)
        payment_id = self._billing.charge(user_id, price_cents)
        try:
            self._access.grant(user_id, course_id)
        except Exception:
            self._billing.refund(payment_id)  # keep the subsystems consistent
            raise
        self._mailer.send_welcome(email, course_id)
        return f"enrolled {user_id} in {course_id} ({payment_id})"


if __name__ == "__main__":
    facade = EnrollmentFacade(Accounts(), Billing(), CourseAccess(), Mailer())
    print(facade.enroll("ola@example.com", "design-patterns", 19_900))

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step by step
  • When to use it and when not to
  • Related patterns
  • In practice
  • Quick check
  • Summary

Create a free account · Sign in