ReadyStack

Design patterns in Java · all 23 GoF patterns

Explainer in three steps. Problem: design pattern books show pseudocode and courses run for hours, so you still cannot tell which pattern fits your code. Design Patterns in Java, e
Design Patterns in Java: all 23 GoF patterns, each one short Java 21 file (22–56 lines) that runsAll 34 tests pass on Java 21 and Java 25. Read every pattern free; the runnable kit is one payment, no subscription.

Use the free versionUnlock the full version

Also on: Whop

Design Patterns in Java: pick the problem in your code, get the pattern as a short Java file that runs

  • All 23 patterns, one short file each. Every GoF pattern is one Java 21 file of 22–56 lines (median 32) with records, sealed types and pattern matching: no getter boilerplate.
  • All 34 tests pass on Java 21 and Java 25. Unzip, run mvn test: 23 JUnit 5 test classes, 0 failures. The output below each example is the real output of that file.
  • Pay once, no subscription. Read every pattern here for free. The full kit (Maven project, 30-page PDF, 69 drills, AI rules) is a one-time purchase.

Full kit $19 one-time · code and explanations in English · Free or full kit?

When to use which design pattern

Find the sentence that matches your code, then click the pattern.

Your code has this situationPatternDo NOT use it whenLines
Creational
One shared object, and a second copy would be a bugNot for things you need to swap in tests (a database, a clock): pass those in instead.22
A base class runs the steps, subclasses choose which object it createsNot when there is only one product class: a constructor or a static factory is enough.32
Several objects must come from the same family (region, theme, database)Not when you have a single product type, or when families never mix: it adds classes for nothing.29
Many optional fields, or the object must be valid before anyone sees itNot for a record with 2-3 fields that are all required: the canonical constructor is clearer.37
New objects start as a copy of a configured templateNot when objects are cheap to construct; and beware shallow copies of mutable fields.28
Structural
A class you cannot edit has the wrong interfaceNot when you own both sides: change the interface instead of adding a translator.28
Two things vary independently and subclasses multiply (kind x channel)Not when one of the two dimensions has only one variant.31
A tree where one item and a group of items should be used the same wayNot when your data is flat, or when leaves and groups need very different operations.25
Add optional behaviour in any combination at run timeNot when the order of extras must not matter: wrappers apply in stack order.30
Callers repeat the same multi-step sequence over several classesNot as a place to hide all logic: a facade coordinates, it should not become a god class.46
Thousands of objects repeat the same heavy dataNot when objects are few or the shared part is small: you add a factory for little gain.32
Control access to a slow, remote or protected object without changing callersNot when the extra layer hides failures callers must handle (network errors behind a 'local' interface).33
Behavioral
A request goes up a line of handlers until one takes itNot when exactly one fixed handler always applies: a direct call is clearer and easier to debug.26
Actions must be queued, logged, retried or undoneNot for one-off calls you never queue or undo: it is extra ceremony.44
Users write rules or formulas in a small language you must evaluateNot for big or fast-changing languages: use a parser generator (ANTLR) or an existing expression engine.56
Walk through items without knowing how they are storedNot when a Stream or an existing collection already gives you what you need.30
Many objects talk to each other and the references tangleNot when the mediator grows into a god object that owns all logic.37
Save and restore an object's state without exposing its fieldsNot when snapshots are large and frequent: store changes (commands) instead.36
When one object changes, others must reactNot when the reaction must happen in a strict order or in one transaction: call it directly.30
Behaviour depends on a status and every method switches on itNot for two or three states with simple rules: an enum and a switch are fine.42
Several interchangeable ways to do one job, chosen at run timeNot when there is one algorithm that never changes.24
Same steps in the same order, only some steps differNot when steps vary freely: pass a Strategy instead of forcing inheritance.34
New operations on a fixed set of types, without editing the typesNot when the set of types changes often: every new type edits every visitor.52

Design patterns interview questions (69, with short answers)

Three per pattern. Say the answer out loud first, then open it.

Singleton 3 questions
Why is an enum the safest Singleton in Java?
The JVM creates the constant once, thread-safely, and enum serialization and reflection cannot make a second one.
What is wrong with lazy init that checks `instance == null` without locking?
Two threads can both see null and build two instances; you need a holder class, an enum, or double-checked locking on a volatile field.
Why do people call Singleton an anti-pattern?
It is hidden global state: callers depend on it without saying so, and tests cannot replace it. Prefer passing the object in (dependency injection).
Factory Method 3 questions
Factory Method vs a static factory method like List.of()?
GoF Factory Method is an overridable instance method that subclasses change; a static factory is one fixed method that hides the constructor.
Factory Method vs Abstract Factory?
Factory Method creates one product through inheritance; Abstract Factory is an object that creates a whole family of related products.
Which SOLID principle does it support?
Open/Closed: a new channel is a new subclass, and the existing notify() code is not edited.
Abstract Factory 3 questions
What is the weak spot of Abstract Factory?
Adding a new product type means adding a method to the interface and to every factory.
How do you choose which concrete factory to use?
Once, at startup (config or dependency injection); the rest of the code only sees the interface.
Can an Abstract Factory be built from Factory Methods?
Yes: each create method on the factory is often a factory method that subclasses implement.
Builder 3 questions
Why not just use setters?
Setters leave a half-built, mutable object visible; a builder hands out the object only after build() validated it.
Where do you validate in a Builder?
In build() for rules across fields (an order needs an item), and in the record's compact constructor for rules that always hold.
Builder vs records with `with` methods?
Records are great for small immutable values; a builder still wins when there are many optional parts or a step-by-step build.
Prototype 3 questions
Shallow copy vs deep copy?
A shallow copy shares the inner objects (the same list); a deep copy copies them too, so changes to the copy never reach the original.
Why do many teams avoid Cloneable?
clone() skips constructors, returns Object, throws a checked exception and copies shallowly by default; an explicit copy() or copy constructor is clearer.
What is a prototype registry?
A map of named ready-made objects (templates) that callers copy instead of building from zero.
Adapter 3 questions
Adapter vs Facade?
Adapter makes one interface fit another that already exists; Facade invents a new, simpler interface over many classes.
Object adapter vs class adapter?
An object adapter holds the old object (composition, the Java norm); a class adapter extends it, which Java only allows for one class.
Adapter vs Decorator?
Adapter changes the interface and keeps the behaviour; Decorator keeps the interface and adds behaviour.
Bridge 3 questions
How many classes do you need for M kinds and N channels?
With Bridge M + N; with subclasses for every combination M x N.
Bridge vs Adapter?
Bridge is designed up front so two sides can grow apart; Adapter is added later to make existing things fit.
Bridge vs Strategy?
The code looks alike (an object holds an interface); Bridge splits a structure in two for the long term, Strategy swaps one algorithm.
Composite 3 questions
Where do child-management methods (add/remove) go?
Either only on the group (type-safe) or on the shared interface (uniform, but leaves must refuse); state your trade-off.
How does a sealed interface help a Composite?
The compiler knows the only kinds are Product and Bundle, so a switch over them is checked for completeness.
Name a risk with deep composites.
Recursion depth and cycles: a bundle that contains itself loops forever unless you guard it.
Decorator 3 questions
Decorator vs inheritance?
Inheritance fixes the extras at compile time; decorators combine them at run time without new classes.
Decorator vs Proxy?
Same shape; a Decorator adds behaviour the caller asked for, a Proxy controls access (cache, lazy load, security) to the same object.
Does wrapper order matter?
Yes. On a 1000-cent item in this kit: coupon then express = 1899, express then coupon = 1800 (both tested).
Facade 3 questions
Does a Facade stop callers from using the subsystems?
No. It offers a simple path; advanced callers may still use the parts directly.
Facade vs Mediator?
Facade is one-way: clients call it and it calls the parts. Mediator is two-way: the parts talk to each other through it.
What bug does the Facade in this kit prevent?
A declined payment releasing the reserved stock: the test checks 1 lamp is left after the decline.
Flyweight 3 questions
What must be true of the shared (intrinsic) part?
It must be immutable, because every user sees the same object.
Why can `Integer a = 127, b = 127; a == b` be true but false for 128?
Integer.valueOf caches -128..127 (a flyweight pool), so 127 is the same object; 128 is a new one. Compare with equals().
Flyweight vs Singleton?
Singleton is one instance of a class; Flyweight is a pool of shared instances, one per distinct value.
Proxy 3 questions
Name four kinds of proxy.
Virtual (lazy creation), remote (stands for an object elsewhere), protection (access checks), caching / smart reference.
How does Spring's @Transactional use this pattern?
Spring wraps the bean in a proxy that opens and commits the transaction around the real method call.
Why does a self-call skip @Transactional?
this.method() calls the real object directly, not the proxy, so the proxy's extra work never runs.
Chain of Responsibility 3 questions
What happens if no handler takes the request?
You must decide: a default (here 'board review'), an exception, or an empty Optional. Never fail silently.
Chain vs Decorator?
A decorator always calls the wrapped object; a handler in a chain may stop the request and not pass it on.
How does Java 8+ make chains short?
Handlers can be lambdas returning Optional, linked with a default method such as then(), as in this kit.
Command 3 questions
How do you implement undo with Command?
Push each executed command on a stack; undo pops the last one and calls its undo(), which restores what execute() changed.
Command vs Strategy?
A Strategy is HOW to do one job (a sort order); a Command is a request to do something, often with its own data and undo.
Why does Clear store the old text?
Clearing destroys information; undo needs the 'before' value, so the command keeps it (a small memento).
Interpreter 3 questions
What are terminal and non-terminal expressions?
Terminals are leaves (numbers, variable names); non-terminals combine other expressions (Add, Mul).
How does Java 21 shorten an interpreter?
A sealed interface of records for the grammar and one switch with record patterns for eval; the compiler checks every case is handled.
Where does operator precedence live?
In the parser's grammar: product is parsed inside sum, so '2 + 3 * 4' becomes Add(2, Mul(3, 4)) = 14.
Iterator 3 questions
What is a fail-fast iterator?
ArrayList's iterator throws ConcurrentModificationException if the list is changed during iteration, except through the iterator itself.
What must next() do at the end?
Throw NoSuchElementException, as the Iterator contract says (tested in this kit).
Internal vs external iteration?
External: the caller pulls items with next(). Internal: the collection pushes items to your lambda (forEach, streams).
Mediator 3 questions
Mediator vs Observer?
Observer broadcasts one subject's changes to subscribers; Mediator centralises two-way talk between peers.
Main risk of a Mediator?
All the coordination logic moves into one class, which can become huge; split it by use case.
Give a real-world mediator.
An airport control tower: planes talk to the tower, not to each other.
Memento 3 questions
Who are the three roles?
Originator (the cart, makes and reads snapshots), Memento (the snapshot), Caretaker (the history that only stores them).
Why must the snapshot copy the list?
Otherwise later changes to the cart change the 'saved' state too; List.copyOf makes it immutable (tested).
Memento vs Command for undo?
Memento stores whole states (simple, more memory); Command stores how to reverse each change (less memory, more code).
Observer 3 questions
What memory leak does Observer cause?
The subject holds strong references to listeners; if they never unsubscribe they can never be garbage collected (lapsed listener).
Push vs pull model?
Push sends the new data with the event (here the Status); pull only says 'changed' and listeners ask the subject.
Why was java.util.Observable deprecated?
It is a class, not an interface (you must extend it), it is not serializable, and its events are weakly defined.
State 3 questions
State vs Strategy?
Same shape; in State the states replace each other as the object moves on, in Strategy the caller picks an algorithm.
Who decides the next state?
Here each state returns the next one (New.pay() returns Paid). The other option is the context deciding; say which you chose.
Why use a sealed interface for states?
The compiler knows every state, so a switch over them is checked and nobody adds a state outside the file.
Strategy 3 questions
How do lambdas change Strategy?
A strategy is often a functional interface, so each algorithm is a one-line lambda instead of a class.
Strategy vs Template Method?
Strategy swaps a whole algorithm by composition at run time; Template Method fixes the steps and lets subclasses fill some in.
Where do strategies come from at run time?
A map by name (as in this kit), configuration, or dependency injection.
Template Method 3 questions
Why make the template method final?
So no subclass can change the order of the steps; they may only fill in the steps they are given.
What is a hook?
An optional step with a default (footer() returns "" here) that subclasses may override.
Which principle does Template Method show?
The Hollywood principle: don't call us, we'll call you; the base class calls the subclass steps.
Visitor 3 questions
What is double dispatch?
The method run depends on two runtime types: item.accept(v) picks the item type, then v.visitBook(this) picks the visitor.
What does Java 21 change for Visitor?
With sealed types and pattern matching a switch over the item type is checked for completeness, often replacing the visitor classes.
When is Visitor a bad fit?
When you add types more often than operations: each new type forces a change in every visitor.

Free here, or take the whole kit with you

Free on this page

  • All 23 patterns: problem, idea, when not to use it, the code smell it replaces
  • The full Java file of each pattern and its real output
  • When-to-use chart and 69 interview questions with answers

Questions

Which Java version do I need?

Java 21 or newer. Every file was compiled with -Xlint:all -Werror and run on JDK 21 and JDK 25 with the same output. run-all.sh tells you if your Java is older.

Do I need Maven?

No. run-all.sh / run-all.cmd compile with javac and run all 23 examples, and any single file runs with java File.java. Maven is only for the JUnit tests (mvn test).

Which IDE?

Any: open the folder as a Maven project in IntelliJ IDEA, Eclipse or VS Code; every example has a main method.

Can I use the code at work?

Yes, copy it into your own projects. Please do not resell the kit itself.

More tools for developers and students

See all tools

This tool is 1 of 298 paid tools in English. All 298 with one key: Freelancer & Small Business Pass — $9.99/month · $79/year · Deadline reminders by email (free)

Email me this result
A copy of what you see above, in your inbox — the tool stays free, nothing here is locked.

More tools for the same work

AI Video Clipper for Shorts, No CreditsAI video clipper for Shorts with no credits: best 9:16 clips ranked, nothing uploadedFree version
People like you also use
Everything for Developers and compliance teams → · ReadyStack Pass — every tool in one subscription · All tools →