Fasada (Facade) – jedno proste wejście do skomplikowanego podsystemu
Fasada udostępnia jedną wygodną operację, która w środku koordynuje wiele klas podsystemu. Przykład zapisu na kurs z płatnością, dostępem i e-mailem powitalnym w C#, TypeScript, Javie, Go i Pythonie.
Żeby zapisać studenta na kurs, trzeba znaleźć albo utworzyć konto, pobrać płatność, nadać dostęp do materiałów i wysłać e-mail powitalny – w tej kolejności i z obsługą błędów pomiędzy. Fasada (ang. Facade) zamyka tę choreografię w jednej metodzie enroll(), dzięki czemu kontroler, zadanie wsadowe i panel administratora nie muszą znać czterech klas ani ich wzajemnych zależności.
- 4
- klasy podsystemu – konta, płatności, dostęp, poczta
- 1
- wywołanie dla klienta – enroll(email, kurs, cena)
- 0
- zmian w podsystemie – fasada tylko go koordynuje
Problem: każdy klient zna całą choreografię
Platforma kursów ma trzy miejsca, w których student zostaje zapisany: zakup na stronie, import listy uczestników od firmy i ręczne dodanie przez administratora. Każde z nich wygląda mniej więcej tak:
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);Kod jest skopiowany trzy razy i w każdym miejscu nieco inny. W panelu administratora ktoś zapomniał o zwrocie pieniędzy przy błędzie nadawania dostępu, a import firmowy nie wysyła e-maili. Gdy dojdzie nowy krok – na przykład dodanie do kanału społeczności – trzeba będzie znaleźć i poprawić wszystkie kopie.
Rozwiązanie: jedna klasa, która zna kolejność
Tworzymy EnrollmentFacade z jedną metodą enroll(email, courseId, priceCents). Fasada otrzymuje klasy podsystemu w konstruktorze i wywołuje je we właściwej kolejności, łącznie z kompensacją (zwrotem płatności), gdy coś pójdzie nie tak. Wszyscy trzej klienci wołają tylko fasadę.
| Rola | W przykładzie | Odpowiedzialność |
|---|---|---|
| Fasada (Facade) | EnrollmentFacade | zna kolejność kroków i deleguje do podsystemu |
| Klasy podsystemu | Accounts, Billing, CourseAccess, Mailer | właściwa praca; nic nie wiedzą o fasadzie |
| Klienci | kontroler zakupu, import, panel admina | korzystają z jednej operacji wysokiego poziomu |
Implementacja w pięciu językach
Klasy podsystemu są tu celowo uproszczone – w prawdziwym systemie to osobne moduły, często z własnymi bazami albo zewnętrznymi API. Ważne jest to, co robi fasada: ustala kolejność, obsługuje kompensację i zwraca klientowi jeden, zrozumiały wynik.
EnrollmentFacade
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})";
}
}// 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));// 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));
}
}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))
}# 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))Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Krok po kroku
- Kiedy stosować, a kiedy nie
- Powiązania z innymi wzorcami
- W praktyce
- Szybki test
- Podsumowanie