Này đúng là kim chỉ nam cho developers, mỗi khi đi phỏng vấn thì phải mở ra ngó tí.
- Creational (5)
- Singleton: One instance, global access. Lazy, Eager, Enum.
- Builder
- The Factory Method
- Abstract Factory
- Prototype
- Structural (7)
- Adapter: new class got method call old code
- Bridge: separate abstraction and implementation
- Composite:
File,Folder,List<Interface> - Decorator: wrapper Coffee, SimpleCoffee, CoffeeDecorator, MilkDecorator, SugarDecorator implement cost()
- Facade (One door - one method, everything inside)
- Flyweight (Cache)
- Proxy: access control: lazyload, cache proxy, remote proxy, protection proxy.
- Behavioral
I. Creational Pattern
1. Singleton
Singleton: a class has only one instance and provides a global access.
It's typically used for shared resources like configuration, logging, or connection pools.
The key implementation: private constructor, providing a static instance, and ensuring thread safety — usually via eager initialization, synchronized access, or double-checked locking.
However, Singleton should be used carefully because it introduces global state and can make testing harder.
2. Builder
The Builder Pattern is that constructs complex objects have got many parameters.
3. Factory Method
The Factory Method is that defines an interface for creating an object, but lets subclasses decide which concrete class to instantiate.
Instead of using new directly, object creation is delegated to a factory method.
This promotes loose coupling, follows the Open/Closed Principle, and makes the code easier to extend without modifying existing logic.
Overall: one Abstract method return Interface (A) and one method call abstract method A.concrete class will be define which concrete class implement that Interface will be call.
4. Abstract Factory
Factory Method → creates one product
Abstract Factory → creates a family of related products
Example:
- Factory Method --> payment
- Abstract Factory --> Button + Checkbox + Menu
5. Prototype
that lets you create new objects by copying (cloning) an existing object. extends Cloneable
II. Structural Pattern
1. Adapter
Adapter: Convert interface so old code can work with new code
Old code: 1 class
Convert: a new Interface và put old code into a new class implement Interface.
Overall: Put old class into a new class implement Interface.
2. Bridge
Bridge = “separate abstraction and implementation so both can change independently”
Abstract Class:
- Define Interface via Constructor and got Abstract method
- Concrete class define concreate interface by Constructor and call it via abstract method.
3. Composite
Composite = "contain list interface, for each call the interfaces"
Example: File and Directory are implements FileSystemComponent, and Directory can contain Directory and Files (List<FileSystemComponent> in Directory)
4. Decorator
Decorator = "dynamically add new behavior to an object without modifying its class." Wrapping the original object in a decorator class that implements the same interface
Example: SimpleCoffee, CoffeeDecorator, MilkDecorator, SugarDecorator.
5. Facade
Facade = “one simple interface to a complex system” -- One door. Put everything in the one method
6. Flyweight
Flyweight = “share common data to save memory” - cache (public static Map and method)
7. Proxy
Proxy = “control access to an object” - lazy load
public void display() {
if (realImage == null) {
realImage = new RealImage(filename); // lazy loading
}
realImage.display();
}
III. Behavioral Pattern
1. Chain of Responsibility (Filter, middleware, request processing flows)
2. Command
Command = encapsulates a request as an object, decouples the sender (Invoker) from the receiver (business logic). Example: Remote Control, TV, TurnOnCommand 👉 The remote doesn’t know how TV works, it just calls execute()
3. Interpreter
Interpreter = định nghĩa một ngôn ngữ (grammar) và cung cấp cách diễn giải (interpret) các câu lệnh của ngôn ngữ đó. Interpreter is a design pattern that defines a grammar for a language and provides an interpreter to evaluate sentences in that language.
4. Iterator
Iterator = cho phép bạn duyệt (traverse) các phần tử của một collection tuần tự mà không cần biết cấu trúc bên trong của collection đó. Iterator = allows sequential traversal of a collection without exposing its internal structure.
Tách logic duyệt khỏi collection, Client chỉ cần: hasNext(), next(). Không cần biết collection là: Array, List, Tree, Graph.
5. Mediator
Mediator = giảm sự phụ thuộc trực tiếp giữa các object, bằng cách đưa toàn bộ giao tiếp qua một mediator (trung gian). Mediator = centralizes communication between objects by introducing a mediator object, reducing direct dependencies between them.
Ý tưởng: Thay vì các object gọi trực tiếp nhau. Tất cả giao tiếp sẽ đi qua Mediator (Chat server: Slack, Messenger, Discord, ...)
Khi nào dùng:
- Khi có nhiều object giao tiếp phức tạp với nhau (N×N dependency)
- Khi muốn centralize communication logic
Pros
- Giảm coupling mạnh
- Dễ thay đổi logic giao tiếp
Cons
- Mediator có thể trở thành God object
- Logic dồn vào một chỗ → khó maintain nếu quá lớn
Mediator vs Observer
- Observer: publish-subscribe (1 → nhiều)
- Mediator: nhiều object giao tiếp qua trung gian
Mediator vs Facade
- Facade: đơn giản hóa interface
- Mediator: điều phối giao tiếp giữa object
6. Memento
Memento = cho phép bạn lưu và khôi phục trạng thái (state) của object mà không làm lộ chi tiết nội bộ (encapsulation). Memento = captures and restores an object's internal state without violating encapsulation.
Ý Tưởng
- Lưu snapshot của object tại một thời điểm (Save/Load game)
- Có thể rollback / undo về trạng thái trước (undo/Redo trong editor)
Memento vs Command
- Memento: lưu state
- Command: lưu action để replay
7. Observer
Observer = “one-to-many notification”
List <Interface> like Composite pattern
8. State
State = cho phép một object thay đổi hành vi (behavior) của nó khi trạng thái nội bộ (state) thay đổi
State = allows an object to change its behavior when its internal state changes, by delegating behavior to state-specific classes.
9. Strategy
Strategy = cho phép bạn định nghĩa một họ các thuật toán (algorithms), đóng gói mỗi thuật toán vào một class riêng, và có thể thay đổi (swap) chúng tại runtime.
Strategy = defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime.