Design Patterns
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
- Structural
- 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.
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