Cheat sheet
Tóm tắt toàn bộ pattern trên một trang: mục đích và ý cần ghi nhớ. Có thể in hoặc lưu thành PDF để tra cứu nhanh.Every pattern on one page: its intent and the key takeaway. Print it or save it as a PDF for quick reference.
Khởi tạoCreational
5- SingletonĐảm bảo cả ứng dụng chỉ có đúng một instance và một điểm truy cập chung tới nó.Ensure the whole app has exactly one instance and one shared access point to it.Một mà thôi — nhưng đừng biến nó thành biến toàn cục trá hình.Only one — but don't let it become a global variable in disguise.
- Factory MethodGiao việc tạo object cho một method riêng để lớp con hoặc cấu hình quyết định tạo loại nào.Hand object creation to a dedicated method so subclasses or config decide which type to build.Quy trình giữ nguyên, khâu 'new' để người khác quyết.Keep the flow, let someone else decide the `new`.
- BuilderLắp ráp object phức tạp từng bước, đặt tên rõ ràng cho từng tham số, chỉ khai báo những gì khác mặc định.Assemble a complex object step by step, naming each parameter and setting only what differs from defaults.Gọi món theo tên, không theo thứ tự.Order by name, not by position.
- Abstract FactoryMột factory tạo ra cả một họ object đi cùng nhau, đảm bảo chúng luôn 'cùng bộ' với nhau.One factory creates a whole family of related objects, guaranteeing they always match each other.Chọn hãng một lần, cả bộ tự khớp.Pick the brand once, the whole set matches.
- PrototypeTạo object mới bằng cách sao chép một object mẫu đã cấu hình sẵn, rồi chỉ sửa phần khác biệt.Create new objects by copying a pre-configured sample object, then changing only what differs.Save as, đừng sửa bản gốc — và nhớ copy sâu.Save as, never edit the master — and copy deep.
Cấu trúcStructural
7- AdapterBọc một interface 'lạ' (SDK bên thứ ba, code cũ) để nó khớp với interface mà code của bạn mong đợi.Wrap a 'foreign' interface (third-party SDK, legacy code) so it fits the interface your code expects.Không sửa ai cả — chỉ thêm cục chuyển đổi ở giữa.Change no one — just plug a converter in between.
- DecoratorBọc object trong các lớp vỏ cùng interface để thêm hành vi (cache, log, transaction...) mà không sửa object gốc.Wrap an object in layers sharing its interface to add behaviour (cache, logging, transactions...) without changing it.Cùng interface, bọc thêm một lớp, mỗi lớp một việc.Same interface, one more layer, one job per layer.
- FacadeMột cửa trước đơn giản che đi cả mớ subsystem phức tạp phía sau.One simple front door that hides a tangle of subsystems behind it.Một cửa, một nút bấm — phía sau là cả nhà máy.One door, one button — a whole factory behind it.
- ProxyMột object đứng thế chỗ object thật, cùng interface, để kiểm soát mọi lời gọi tới nó.A stand-in with the same interface as the real object, controlling every call to it.Cùng gương mặt, khác người gác cổng.Same face, different gatekeeper.
- CompositeXếp object thành cây và đối xử với một phần tử lẻ hay cả nhóm theo cùng một cách.Arrange objects into trees and treat a single item and a whole group the same way.Một lá hay cả cành — cứ hỏi price() là xong.A leaf or a whole branch — just ask price().
- BridgeTách 'cái gì' khỏi 'làm bằng cách nào' thành hai nhánh độc lập, nối bằng composition.Split 'what' from 'how' into two independent hierarchies joined by composition.Hai chiều thay đổi, hai cây riêng — nối bằng một field.Two axes of change, two trees — joined by one field.
- FlyweightDùng chung phần dữ liệu nặng, bất biến giữa hàng nghìn object để tiết kiệm bộ nhớ.Share the heavy, immutable part of thousands of objects to save memory.Phần nặng dùng chung, phần nhẹ mỗi người một bản.Share the heavy part, copy only the light part.
Hành viBehavioral
11- StrategyĐóng gói từng thuật toán thành object riêng để hoán đổi lúc chạy.Wrap each algorithm in its own object so you can swap them at runtime.Cùng một việc, nhiều cách làm — cắm cách nào chạy cách đó.Same job, many ways — plug in a way, run that way.
- ObserverKhi một object thay đổi, mọi object đăng ký theo dõi được báo tự động — mà nó không cần biết họ là ai.When one object changes, every subscriber is notified automatically — without it knowing who they are.Đừng gọi tôi, tôi sẽ báo bạn.Don't call me, I'll notify you.
- Template MethodCố định khung các bước của một thuật toán, chỉ để trống vài bước cho lớp con hoặc callback điền vào.Fix the skeleton of an algorithm and leave a few steps for subclasses or callbacks to fill in.Khung cố định, chỗ trống tuỳ biến — đừng gọi tôi, tôi sẽ gọi bạn.Fixed skeleton, pluggable blanks — don't call us, we'll call you.
- CommandBiến một yêu cầu thành object để lưu, xếp hàng, ghi log hoặc undo.Turn a request into an object so you can store, queue, log or undo it.Yêu cầu thành tờ phiếu — cất được, xếp được, huỷ được.Requests become tickets — store them, queue them, cancel them.
- StateObject đổi hành vi khi trạng thái bên trong đổi — mỗi trạng thái là một object riêng.An object changes behaviour when its internal state changes — each state is its own object.Trạng thái nào luật nấy — trạng thái tự chỉ đường sang trạng thái kế.Each state, its own rules — the state points to the next one.
- Chain of ResponsibilityChuyền yêu cầu qua một chuỗi handler — mỗi mắt xích tự xử lý, chuyền tiếp hoặc chặn lại.Pass a request along a chain of handlers — each link handles it, passes it on, or stops it.Mỗi trạm một việc: làm, chuyền, hoặc chặn.One job per checkpoint: handle, pass, or block.
- IteratorDuyệt từng phần tử của một tập hợp mà không cần biết nó được lưu (hay tải) ra sao.Walk through a collection one element at a time without knowing how it's stored (or loaded).Chỉ cần hỏi 'còn không?' và 'cho cái tiếp'.Just ask 'any more?' and 'give me the next'.
- MediatorCác object không nói chuyện trực tiếp với nhau mà đi qua một trung gian điều phối.Objects stop talking to each other directly and go through one coordinating middleman.Đừng gọi nhau — gọi tổng đài.Don't call each other — call the switchboard.
- MementoChụp lại trạng thái của object để khôi phục sau, mà không phơi bày bên trong nó.Capture an object's state to restore it later, without exposing its internals.Chụp lại, cất đi, khôi phục — nhưng đừng mở ra xem.Snap it, stash it, restore it — but don't peek inside.
- VisitorThêm thao tác mới cho cả một họ kiểu dữ liệu mà không sửa các kiểu đó.Add new operations to a whole family of types without editing those types.Kiểu đứng yên, thao tác đi thăm.Types stay put, operations come visiting.
- InterpreterBiểu diễn một ngôn ngữ nhỏ bằng cây object, mỗi luật ngữ pháp là một class biết tự 'thông dịch'.Represent a small language as a tree of objects, where each grammar rule is a class that interprets itself.Mỗi luật ngữ pháp một class, câu dài thành cây, tính từ lá lên gốc.One class per grammar rule, sentences become trees, evaluate leaves to root.
Doanh nghiệpEnterprise
12- Dependency InjectionObject không tự new dependency — có người khác tạo sẵn rồi 'tiêm' vào cho nó.Objects don't `new` their dependencies — someone else builds them and injects them in.Đừng tự đi chợ — cứ khai báo cần gì, sẽ có người mang tới.Don't go shopping — declare what you need and it gets delivered.
- RepositoryGiả vờ dữ liệu nằm trong một collection trong bộ nhớ — giấu SQL sau một interface.Pretend your data lives in an in-memory collection — hide the SQL behind an interface.Hỏi thủ thư, đừng tự lục kho.Ask the librarian, don't dig through the warehouse.
- Service LayerMột tầng duy nhất chứa các use case: điều phối repository, transaction và quy tắc nghiệp vụ.One layer holding the use cases: it orchestrates repositories, transactions and business rules.Controller nhận đơn, Service nấu, Repository giữ kho.Controller takes the order, Service cooks, Repository keeps the pantry.
- Data Transfer ObjectObject 'đóng gói' riêng cho việc gửi dữ liệu qua ranh giới — không bao giờ phơi entity ra API.A dedicated 'shipping box' for data crossing a boundary — never expose your entities through the API.Entity ở trong kho, DTO mới ra cửa.Entities stay in the warehouse; DTOs go out the door.
- SpecificationBiến mỗi điều kiện lọc thành một object nhỏ, rồi ghép and/or/not như lắp Lego.Turn each filter condition into a small object, then combine them with and/or/not like Lego.Mỗi điều kiện một viên gạch — xếp and, or, not tuỳ ý.One brick per condition — stack them with and, or, not.
- Unit of WorkGhi lại mọi thay đổi trong một nghiệp vụ rồi commit tất cả cùng lúc — hoặc không gì cả.Track every change in a business operation, then commit them all at once — or nothing at all.Bỏ hết vào giỏ, ra quầy tính tiền một lần.Fill the basket, pay once at the till.
- Retry with Exponential BackoffGọi lại khi gặp lỗi tạm thời, mỗi lần chờ lâu gấp đôi và thêm chút ngẫu nhiên.Re-run a call on transient failures, waiting twice as long each time plus some randomness.Lỗi tạm thì đợi gấp đôi, lệch chút cho khỏi đụng nhau; lỗi thật thì dừng ngay.Transient? Wait double, add jitter. Permanent? Stop now.
- Circuit BreakerNgắt mạch khi dịch vụ phụ thuộc lỗi liên tục, trả lời nhanh bằng fallback thay vì chờ chết chùm.Trip the circuit when a dependency keeps failing and answer fast with a fallback instead of failing together.Lỗi nhiều thì ngắt, đợi nguội thì thử, thử ổn thì đóng.Fail a lot — trip. Cool down — probe. Probe OK — close.
- CQRSTách mô hình GHI (command) và mô hình ĐỌC (query) để tối ưu từng bên riêng.Split the WRITE model (commands) from the READ model (queries) so each can be optimised on its own.Ghi cho đúng, đọc cho nhanh — mỗi bên một mô hình.Write it right, read it fast — one model each.
- Event SourcingKhông lưu trạng thái hiện tại — lưu chuỗi sự kiện đã xảy ra, rồi phát lại để tính ra trạng thái.Don't store the current state — store the sequence of events that happened, and replay them to get the state.Chỉ thêm, không sửa; trạng thái là tổng các sự kiện.Append, never update; state is the sum of events.
- Transactional OutboxGhi dữ liệu nghiệp vụ và event vào cùng một transaction DB, rồi một relay đẩy event sang broker.Write the business row and the event in one DB transaction, then a relay pushes the event to the broker.Ghi chung một transaction, gửi đi sau — không bao giờ ghi hai nơi cùng lúc.Write together in one tx, send later — never dual-write.
- SagaChia giao dịch xuyên nhiều service thành chuỗi bước cục bộ, lỗi thì chạy bước bù trừ theo chiều ngược lại.Split a cross-service transaction into local steps; on failure, run compensating steps in reverse.Mỗi bước một giao dịch nhỏ, mỗi bước một nút 'huỷ' — hỏng thì huỷ ngược về đầu.Each step a small transaction, each step an 'undo' — fail, then undo back to the start.
Đồng thờiConcurrency
10- Producer-ConsumerBên sinh việc bỏ vào hàng đợi, bên xử lý lấy ra — hai bên chạy độc lập, khác tốc độ.Producers put work into a queue, consumers take it out — both run independently at their own pace.Một bên bỏ vào, một bên lấy ra — hàng đợi ở giữa làm giảm xóc.One side puts, one side takes — the queue in between is the shock absorber.
- Worker PoolDùng N worker cố định để xử lý hàng nghìn job — song song nhưng có giới hạn.Use a fixed N workers to process thousands of jobs — parallel, but bounded.Việc thì vô hạn, thợ thì có hạn — N thợ thay phiên rút việc.Jobs are endless, workers are few — N workers take turns pulling jobs.
- Future / PromiseKhởi động việc chậm ngay bây giờ, nhận về một 'phiếu hẹn' để lấy kết quả sau.Start slow work now and get an 'IOU' you can redeem for the result later.Gọi trước, lấy sau — đừng đứng chờ ở quầy.Order now, collect later — don't wait at the counter.
- PipelineChia việc xử lý thành chuỗi các công đoạn nối nhau, mỗi công đoạn chạy song song với công đoạn khác.Split processing into a chain of connected stages, each running concurrently with the others.Mỗi trạm một việc, hàng chạy liên tục qua băng chuyền.One job per station, items flow down the conveyor.
- Fan-out / Fan-inChia việc ra nhiều goroutine/thread chạy song song (fan-out), rồi gộp kết quả về một mối (fan-in).Spread work across many goroutines/threads in parallel (fan-out), then merge the results into one stream (fan-in).Toả ra để làm nhanh, gom về để cộng đúng.Spread out to go fast, gather in to add up right.
- Cancellation / ContextTruyền tín hiệu huỷ và deadline xuống mọi tác vụ con để không ai làm việc vô ích.Propagate cancel signals and deadlines down to every sub-task so nobody works for nothing.Cha huỷ thì con nghỉ — nhưng con phải tự nghe.Parent cancels, children stop — but children must listen.
- SemaphorePhát N 'vé' để giới hạn tối đa N tác vụ cùng chạm vào một tài nguyên tại một thời điểm.Hand out N 'tickets' so at most N tasks touch a resource at the same time.Lấy vé rồi vào, xong việc trả vé — trả trong finally/defer.Take a ticket, go in, give it back — in finally/defer.
- Rate LimiterGiới hạn số thao tác trong mỗi khoảng thời gian, vẫn cho phép một 'cú bùng' (burst) nhỏ.Cap how many operations happen per unit of time, while still allowing a small burst.Xô đầy token, rót đều tay — lấy được token mới được chạy.A bucket of tokens, refilled steadily — no token, no go.
- Read-Write LockCho nhiều người đọc cùng lúc, nhưng người ghi thì phải độc quyền.Many readers at once, but a writer gets exclusive access.Đọc thì chung bàn, ghi thì đóng cửa.Readers share the table, writers close the door.
- Publish-SubscribePublisher gửi message vào một topic; mọi subscriber của topic đó đều nhận một bản, không ai biết ai.Publishers send messages to a topic; every subscriber of that topic gets a copy, and nobody knows anybody.Đăng một lần, ai theo dõi thì nhận — người đăng không cần biết ai nghe.Post once, every follower receives — the poster never knows who listens.