GoF Design Patterns in Java: The Complete Guide (All 23 Patterns)

The Gang of Four book — Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson, Vlissides, 1994) — catalogued 23 patterns across three categories. Thirty years later, these patterns remain the shared vocabulary of object-oriented design. Every pattern in this series has a dedicated article with full runnable Java 17 code, a UML diagram, console output, and real JDK usage examples.

💡 How to use this guide: Each pattern link below goes to a standalone article. If you’re new to patterns, start with Singleton (simplest), then Strategy (most practical), then Observer (most commonly needed). If you’re preparing for a design interview, work through all three categories in order. Source code for every pattern is at ankurm.com/git.app/asmhatre/design-patterns.

Continue reading GoF Design Patterns in Java: The Complete Guide (All 23 Patterns)

Visitor Design Pattern in Java: Complete Guide with Examples

Your codebase has a shape hierarchy: Circle, Rectangle, Triangle. Each is stable — you rarely add new shapes. But you keep adding operations: calculate area, calculate perimeter, export to SVG, check collision, generate bounding box. Each new operation could be added as a method on every shape class. But that means touching three files every time you add an operation, and it couples rendering logic into the geometry classes.

Visitor inverts the structure: each operation is its own class. The shape hierarchy stays closed to modification; you add operations by adding new visitor classes. This is the open/closed principle applied to a class hierarchy — closed to modification, open to new operations.

Continue reading Visitor Design Pattern in Java: Complete Guide with Examples

Template Method Design Pattern in Java: Complete Guide with Examples

Every data migration your team runs follows the same high-level script: connect to the source, read the data, transform it for the target, write it, disconnect. The script never changes. What changes is how each step is carried out — a CSV migration reads files, an API migration makes HTTP calls. The Template Method pattern puts the invariant sequence in one place (an abstract base class) and delegates the varying steps to subclasses. You can’t accidentally reorder the steps, and you can’t forget a step — the skeleton enforces the contract.

This pattern is sometimes dismissed as “just inheritance” — and when overused it can lead to deep, fragile hierarchies. Used well, it’s one of the cleanest ways to express a fixed process with variable implementations. The JDK uses it in HttpServlet, AbstractList, and InputStream.

Continue reading Template Method Design Pattern in Java: Complete Guide with Examples

Strategy Design Pattern in Java: Complete Guide with Examples

A navigation app calculates routes. For walking, shortest distance matters most. For driving, traffic matters. For cycling, elevation change and bike lanes matter. If you put all three algorithms in one class and switch between them with a flag, every algorithm change requires recompiling and re-testing the whole class — and adding a fourth mode means touching the existing code. The Strategy pattern encapsulates each algorithm in its own class and lets the caller swap them at runtime, with zero changes to the surrounding code.

This is one of the most practical patterns in the GoF catalogue. Java’s Comparator, Comparator.comparing(), and the entire java.util.function package are functional implementations of the Strategy pattern. Understanding the structural form first makes the lambda shorthand more meaningful.

Continue reading Strategy Design Pattern in Java: Complete Guide with Examples

State Design Pattern in Java: Complete Guide with Examples

A vending machine behaves differently depending on whether it’s idle, has money inserted, is dispensing an item, or is out of stock. Without the State pattern, you end up with a single class whose methods contain if-else chains that check the current state variable. When a new state is added, you hunt through every method to add the new branch. The State pattern moves each state’s behaviour into its own class, so adding a new state means adding one class and touching nothing else.

The pattern makes an implicit state machine explicit. Instead of a String currentState field and branching logic spread across every method, you have a reference to a State object whose methods implement exactly the right behaviour for that state. The context just delegates to whatever state object it currently holds.

Continue reading State Design Pattern in Java: Complete Guide with Examples

Observer Design Pattern in Java: Complete Guide with Examples

Your stock monitoring service tracks a price. Ten different components care when it changes: a risk alert, two portfolio trackers, a chart renderer, an audit log. If the price object calls each one directly, it must know about all ten. Add an eleventh component and you modify the stock object — which should know nothing about UI renderers or audit logs. The Observer pattern inverts this: components register their interest, and the stock object notifies whoever is listening without knowing who that is.

This is the backbone of event-driven programming. Every GUI event listener, every reactive stream, every message bus, every Spring application event — they all implement the same Observer structure. Learning it from first principles makes all of those systems immediately legible.

Continue reading Observer Design Pattern in Java: Complete Guide with Examples

Memento Design Pattern in Java: Complete Guide with Examples

Undo is a feature users take for granted but developers often implement badly. The naive approach — saving the entire object state as a public snapshot — violates encapsulation: once you expose internal state for storage, anything can read and modify it. The Memento pattern solves this by defining a dedicated snapshot object whose contents only the originator can read. The caretaker (your undo manager) stores and returns mementos without ever opening them.

This is not just about text editors. Any time you need rollback — database transactions, game save states, configuration checkpoints, wizard “back” buttons — you’re solving the same problem the Memento pattern addresses.

Continue reading Memento Design Pattern in Java: Complete Guide with Examples