Java Design Patterns - Revision Notes
1. Singleton Pattern
Intent: Ensure only one instance of a class exists and provide a global point of access.
Structure: Private constructor, static instance, and public accessor method.
Implementations:
- Eager Initialization
- Lazy Initialization (Double-checked locking)
- Static Inner Class
- Enum Singleton (Best, prevents reflection & serialization issues)
Thread Safety: Use synchronized or static inner class.
Can be broken by: Reflection, Cloning, Serialization.
Fix: Use Enum Singleton.
Example:
public enum Singleton { INSTANCE; public void show() { [Link]("Hello");
} }
Use Cases: Logging, Configuration, Cache, Thread Pool, DB Connection.
2. Prototype Pattern
Intent: Create new objects by cloning existing ones (instead of creating from scratch).
Structure: Cloneable interface or copy constructor.
Types: Shallow Copy and Deep Copy.
Example:
public class Employee implements Cloneable { public Employee clone() throws
CloneNotSupportedException { return (Employee) [Link](); } }
Advantages: Reduces expensive object creation.
Disadvantages: Complex for deep cloning.
Use Cases: Object caching, Object pools, Complex object duplication.
3. Template Method Pattern
Intent: Define the skeleton of an algorithm in a base class; subclasses override specific steps.
Structure: Abstract base class with a final template method and abstract hooks.
Example:
abstract class DataProcessor { public final void process(){ read(); transform();
write(); } abstract void read(); abstract void transform(); abstract void write(); }
Advantages: Code reuse, enforces consistent algorithm steps.
Disadvantages: Rigid structure, less flexible at runtime.
Use Cases: File parsing, Report generation, Framework hooks.
4. Iterator Pattern
Intent: Provides a way to traverse elements of a collection without exposing its structure.
Structure: Iterator interface with methods hasNext() and next().
Example:
Iterator it = [Link](); while([Link]()){ [Link]([Link]()); }
Advantages: Hides internal structure, supports different traversal methods.
Disadvantages: Fail-fast issue in concurrent modification.
Use Cases: Collection traversal, custom data structures, database cursors.
5. Chain of Responsibility Pattern
Intent: Pass request along a chain of handlers; each handler decides to process or forward it.
Structure: Abstract handler defines setNext() and handle() methods.
Example:
abstract class Handler { private Handler next; public void setNext(Handler next){
[Link] = next; } public void handle(String req){ if(!process(req) && next !=
null) [Link](req); } abstract boolean process(String req); }
Advantages: Loose coupling, flexible request processing order.
Disadvantages: Harder debugging, performance impact if chain is long.
Use Cases: Logging, Authentication filters, Servlet filters, Middleware, Validation chains.