L39 — Design Patterns trong Go
Ba module tương tác cho 3 pattern phổ biến nhất trong Go production:
Functional Options (constructor sạch), Middleware Chain
(decorator HTTP), và Strategy (interface swap-able). Mở
file:// là chạy được — không cần build.
1. Functional Options — build Server bằng option
Bật/tắt từng option, sửa giá trị, xem code call-site và struct kết quả thay đổi. So sánh "trước" (constructor positional) với "sau" (options sạch).
Call-site (idiomatic)
Server sau khi build
So với constructor positional (cách "tệ")
2. Middleware Chain — request đi qua decorator
Compose Recover(Logger(Auth(handler))). Request đi từ ngoài vào trong,
response quay ngược ra. Toggle "có Authorization?" và "handler có panic?" để xem
flow đổi.
3. Strategy — swap thuật toán giữ nguyên caller
Cùng một hàm SaveBlob(c Compressor, data) nhưng đổi concrete strategy
thì output khác hẳn. Caller không biết, không quan tâm — chỉ phụ thuộc interface.