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.

Creational Patterns

Creational patterns abstract the object creation process. They make systems independent of how objects are created, composed, and represented. Use them when the exact types and dependencies of the objects your code must work with are unknown ahead of time, or when you want to delegate the responsibility for object creation to specialised classes.

PatternIntentClassic use case
Factory MethodSubclasses decide which object to createFramework plug-in points, notification senders
Abstract FactoryCreate families of related objects without concrete classesCross-platform UI toolkits, theme systems
BuilderConstruct complex objects step by stepSQL query builders, HTTP request builders, Lombok @Builder
PrototypeClone objects instead of creating from scratchDeep-copy expensive objects, template instances
SingletonGuarantee one instance per JVMConfiguration objects, connection pools, loggers

Structural Patterns

Structural patterns concern class and object composition. They describe how to assemble objects into larger structures while keeping the structures flexible and efficient. Most structural patterns introduce an indirection layer — a wrapper, bridge, or proxy — that lets two otherwise incompatible interfaces collaborate.

PatternIntentClassic use case
AdapterMake incompatible interfaces work togetherThird-party library wrappers, InputStreamReader
BridgeDecouple abstraction from implementationJDBC drivers, SLF4J logging facade
CompositeTreat individual objects and compositions uniformlyFile system trees, Swing component hierarchy
DecoratorAdd behaviour by wrapping, not subclassingJava I/O streams, servlet filter chains
FacadeSimplify a complex subsystem with one interfaceSLF4J, JDBC, javax.mail, SDK entry points
FlyweightShare common state among many fine-grained objectsString pool, Integer cache, character rendering
ProxyControl access to an object with a surrogateLazy loading, Spring AOP, JDK dynamic proxy

Behavioral Patterns

Behavioral patterns deal with algorithms and the assignment of responsibilities between objects. They shift focus from structure to communication — how objects interact and distribute work. Most behavioral patterns use interfaces and composition to make the interaction points explicit and swappable.

PatternIntentClassic use case
Chain of ResponsibilityPass a request along a handler chain until handledServlet filter chains, logging handlers, middleware
CommandEncapsulate a request as an object for undo/queuingUndo/redo, job queues, macro recording
InterpreterDefine a grammar and interpret sentences in that languageSQL engines, regex matchers, SpEL, template engines
IteratorTraverse a collection without exposing its internalsJava for-each, cursor-based pagination
MediatorRoute communication through a central coordinatorChat rooms, MVC controllers, event buses
MementoSnapshot and restore object state without breaking encapsulationUndo history, save/load game state, transactions
ObserverNotify dependents automatically when state changesEvent listeners, MVC, reactive streams
StateChange behaviour when internal state changesTraffic lights, vending machines, order workflows
StrategySwap algorithms at runtime via compositionSorting, payment methods, Comparator
Template MethodFix an algorithm skeleton; let subclasses fill stepsHttpServlet, AbstractList, data pipelines
VisitorAdd operations to a hierarchy without modifying itAST processing, shape renderers, export formats

How Patterns Relate

Several patterns look similar on the surface. These distinctions come up often in interviews and code reviews:

Adapter vs. Facade vs. Proxy — Adapter changes the interface of an existing object. Facade creates a new, simpler interface over a subsystem. Proxy preserves the interface but controls access to the real object.

Strategy vs. Template Method vs. State — Strategy swaps the entire algorithm at runtime (composition). Template Method fixes the skeleton and varies the steps (inheritance). State is structurally identical to Strategy but the concrete state can transition itself; the caller doesn’t swap states manually.

Decorator vs. Proxy vs. Composite — Decorator adds behaviour by wrapping (same interface, enhanced). Proxy controls access (same interface, intercepted). Composite is a tree where leaves and branches share an interface so callers treat them uniformly.

Factory Method vs. Abstract Factory vs. Builder — Factory Method delegates object creation to a subclass (one product). Abstract Factory creates families of related products (multiple related products, no concrete types exposed). Builder assembles a single complex product step by step (fine-grained construction control).

Observer vs. Mediator — Observer is a one-to-many notification from a subject to any number of observers; each observer subscribes directly. Mediator is a many-to-many hub: components communicate through the mediator and don’t reference each other at all.

✅ Source Code: Every pattern in this series has a runnable Java 17 project. Clone the repository and compile with the JDK:

git clone https://ankurm.com/git.app/asmhatre/design-patterns.git
cd design-patterns/03-behavioral/strategy
javac *.java -d out && java -cp out strategy.Main

Further Reading

  • Design Patterns: Elements of Reusable Object-Oriented Software — Gamma, Helm, Johnson, Vlissides (Addison-Wesley, 1994) — the original GoF book
  • Head First Design Patterns — Freeman & Freeman — accessible introduction with visual examples
  • refactoring.guru/design-patterns — excellent visual pattern reference with Java code samples

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.