Design Patterns in Java

Naveen AnamaneniUpdated · 8 min read

When you cook often, you stop inventing every dish from scratch. You learn a few dependable methods, like "make a base, then add spices, then simmer", and reuse them for many recipes. Programmers do the same. Over the years they kept running into the same design problems, and the best answers got names. Those named answers are design patterns. A pattern isn't a piece of code to copy. It's an idea for how to arrange your classes so a common problem stops being a problem.

Where the 23 Patterns Come From

In 1994, four authors (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, often called the "Gang of Four") wrote down 23 patterns they saw again and again in good software. Those 23 are still the shared vocabulary of developers today. When someone in a team says "let's put a facade in front of that", everyone knows what they mean.

The 23 fall into three families, based on the kind of problem they solve:

All 23 patterns in three families
FamilyThe question it answersHow many
CreationalHow do we make objects, cleanly and safely?5
StructuralHow do we fit classes and objects together?7
BehavioralHow do objects share work and talk to each other?11

Creational Patterns: Making Objects

PatternIn plain wordsEveryday comparisonSeen in Java
SingletonOnly one object of this class may ever existA country has one president at a timeRuntime.getRuntime()
Factory MethodLet a subclass decide which object to createEach branch of a courier company picks its own vehicleIterable.iterator() in each collection
Abstract FactoryCreate a whole matching family of objects togetherA furniture showroom that sells a matching sofa, table and chair in one styleDocumentBuilderFactory in XML APIs
BuilderAssemble a complicated object step by stepOrdering a pizza by choosing size, then toppings, then crustStringBuilder, HttpRequest.newBuilder()
PrototypeMake new objects by copying a ready-made onePhotocopying a filled-in form and changing only the nameclone(), copy constructors

Detailed lessons: "Creational Design Patterns", "Singleton Pattern in Java", "Factory Pattern in Java" and "Builder Pattern in Java".

Structural Patterns: Fitting Things Together

PatternIn plain wordsEveryday comparisonSeen in Java
AdapterMake one interface fit another that expects something differentA travel plug adapter for a foreign socketArrays.asList(array)
BridgeKeep "what it does" and "how it's done" in separate class familiesOne TV remote design that works with many TV brandsJDBC: one API, many database drivers
CompositeTreat a group of things the same way as a single thingA folder can hold files and other folders, and both have a sizeGUI containers holding components
DecoratorAdd extra features by wrapping an objectAdding milk, then sugar, to the same cup of coffeenew BufferedReader(new FileReader(...))
FacadeGive one simple front door to a complicated systemOne reception desk instead of visiting every hotel departmentHttpClient hiding sockets and protocols
FlyweightShare small common objects instead of making thousands of copiesEvery seat in a cinema row points to the same "Premium" price cardInteger.valueOf cache, string pool
ProxyA stand-in that controls access to the real objectA receptionist who decides whether you can meet the managerCollections.unmodifiableList, Spring proxies

Detailed lesson: "Structural Design Patterns".

Behavioral Patterns: Sharing the Work

PatternIn plain wordsEveryday comparisonSeen in Java
Chain of ResponsibilityPass a request along a line of handlers until one takes itA refund request goes to the team lead, then the manager, then the directorServlet filters, logging handlers
CommandTurn an action into an object, so it can be stored, queued or undoneA waiter writes your order on a slip and hands it to the kitchenRunnable tasks, undo in editors
InterpreterRepresent a small language as objects that can evaluate itA calculator that understands "50 + 30 - 15"java.util.regex.Pattern
IteratorWalk through a collection without knowing how it's storedTurning pages of a book without caring how it was boundIterator, the for-each loop
MediatorObjects talk through one middle object instead of to each otherPlanes talk to the control tower, not to every other planeChat rooms, java.util.Timer coordinating scheduled tasks
MementoSave an object's state so it can be restored laterA save point in a video gameUndo history, serialization snapshots
ObserverNotify everyone who subscribed when something changesYouTube notifies subscribers when a video is postedEvent listeners, PropertyChangeListener
StateAn object changes its behavior when its internal state changesA traffic light behaves differently when red, green or yellowOrder status flows, media players (play, pause, stop)
StrategySwap one algorithm for another behind the same interfaceChoosing to pay by UPI, card or cash at the same counterComparator passed to sort
Template MethodA fixed recipe of steps where some steps are filled in laterEvery hot drink: boil water, brew, pour, but brewing differsAbstractList, InputStream.read
VisitorAdd new operations to a set of classes without changing themA tax inspector visits different kinds of shops and applies different rulesFileVisitor in java.nio.file

Detailed lessons: "Behavioral Design Patterns", "Strategy Pattern in Java" and "Observer Pattern in Java".

When Not to Use a Pattern

Patterns add classes and indirection. That's worth it only when the problem is real:

  • Don't add a pattern "just in case". A factory around a class that will only ever have one version is clutter.
  • Prefer the simplest thing that works. If a plain method solves it, write the method.
  • Modern Java often needs less ceremony. Lambdas make Strategy and Command one-liners, enums make the safest Singleton, records cut down Builder-style boilerplate, and sealed types with switch can replace many Visitors.

Common Mistakes

Forcing a pattern into a small problem. Three extra classes around ten lines of logic make code harder, not better.

Mixing up similar patterns. Decorator adds features, Proxy controls access, Adapter changes the interface. All three wrap an object, but for different reasons.

Memorizing names without the problem. In interviews, explain the problem first, then the pattern.

Interview Corner

What are design patterns, and how are they classified?

Design patterns are proven, reusable solutions to common software design problems. The classic catalog by the Gang of Four has 23 patterns in three groups. Creational patterns deal with object creation: Singleton, Factory Method, Abstract Factory, Builder and Prototype. Structural patterns deal with combining classes and objects: Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy. Behavioral patterns deal with how objects interact and share responsibility: Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method and Visitor.

Which design patterns does the JDK use?

Many. Singleton in Runtime.getRuntime(), Builder in StringBuilder, Factory methods in List.of and Integer.valueOf, Prototype in clone(), Adapter in Arrays.asList, Decorator in the java.io streams, Flyweight in the Integer cache, Proxy in Collections.unmodifiableList, Iterator in every collection, Strategy in Comparator, Observer in event listeners, Template Method in AbstractList and Visitor in FileVisitor.

Practice

  1. Easy: For each, name the pattern: a travel plug adapter, a save point in a game, a pizza order form, a control tower.
  2. Harder: Pick three patterns from different families and, for each, describe one place in an app you use daily (a food delivery or banking app) where it would fit.

Quick check: Design patterns

4 questions
1How many patterns are in the Gang of Four catalog?
2Which family is about making objects?
3Adding milk and sugar to the same coffee, layer by layer, is like which pattern?
4Planes talking to a control tower instead of to each other is like:

Key Takeaways

Was this tutorial helpful?

Lesson 178 of 482