Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 57 ยท Practice and Interview Prep

Design Patterns Hidden in the JDK and Popular Frameworks

Spot Singleton, Factory, Builder, Decorator, Observer, Iterator, Strategy and more inside the Java standard library and Spring, with runnable examples.

Once you know the patterns, you start seeing them everywhere. The Java standard library and the big frameworks are built from them, and the people who wrote those libraries used patterns because they solve problems that come up again and again. Reading real code with pattern names in mind does two things: it makes the standard library easier to remember, and it shows you what a pattern looks like when it is done well and not as a textbook diagram.

It is also a favorite interview topic. "Name a place where the JDK uses the Decorator pattern" is a common question, and BufferedReader is the answer you want to have ready. This lesson is a tour. Each example is real API; every claim below is something you can check in the documentation.

Pattern names describe intent, and libraries rarely copy the textbook class diagram. Calling something "a Builder" or "a Decorator" is a statement about how it is used, so you may find that experts argue about borderline cases. Treat the lists below as strong, common examples.

A tour of the JDK

Pattern Where you meet it
Singleton Runtime.getRuntime() returns the one Runtime of the JVM
Factory Method List.of, Integer.valueOf, NumberFormat.getInstance, Calendar.getInstance, Executors.newFixedThreadPool
Abstract Factory DocumentBuilderFactory, TransformerFactory, JDBC's Connection creating statements
Builder StringBuilder, Stream.builder(), ProcessBuilder, HttpRequest.newBuilder(), Locale.Builder
Prototype Object.clone() and ArrayList.clone()
Adapter Arrays.asList, InputStreamReader, Collections.list(Enumeration)
Bridge JDBC: the java.sql API on one side, driver implementations on the other
Decorator BufferedReader, DataInputStream, Collections.unmodifiableList and synchronizedList
Facade Files and HttpClient hide streams, channels and sockets behind a few calls
Flyweight Integer.valueOf caching small values, the String pool
Proxy java.lang.reflect.Proxy
Chain of Responsibility java.util.logging passes records up the logger hierarchy and through handlers
Command Runnable and Callable handed to an Executor
Iterator Iterator and Iterable behind the for-each loop
Observer PropertyChangeSupport and PropertyChangeListener, Swing event listeners
Strategy Comparator given to sort, RejectedExecutionHandler
Template Method AbstractList, AbstractMap, InputStream.read(byte[]) built on read()
Visitor FileVisitor with Files.walkFileTree, ElementVisitor in annotation processing

Run the next example to see several of them at work. Read each block, then compare it with the output.

Java Patterns in java.base

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few lines deserve a second look. Arrays.asList is an adapter because it does not copy: the returned list is a view, so changing it changes the array. Collections.unmodifiableList is a decorator because it implements the same List interface, forwards reads and refuses writes. The Integer cache is a flyweight: values from -128 to 127 are shared objects, which is why comparing boxed integers with == works for 127 and fails for 128. Always use equals for boxed values.

Patterns behind the collections and I/O

Iterator and Template Method in collections. AbstractList implements most of List for you. You supply get(int) and size(), and the base class builds iterator(), contains, indexOf, toString and more on top. That is Template Method: the base class owns the algorithm skeleton, subclasses fill in the steps.

Decorator in I/O. The classic java.io design starts with a simple stream and wraps it: a file stream gets a buffer, the buffer gets a decoder, and so on. Each layer has the same abstraction (InputStream, Reader), so layers stack in any order.

Proxy via reflection. java.lang.reflect.Proxy creates, at run time, an object that implements an interface and sends every call to one handler. This is how many frameworks add logging, security or transactions without changing your class.

Java Dynamic Proxy, Template Method and Command

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

squares is only two small methods, yet toString, contains and indexOf all work, because AbstractList calls your get and size from its own algorithms. The queue holds Runnable objects, which are commands: each one packages an action so it can be stored, delayed or run on another thread by an Executor.

Patterns in Spring

Spring is largely a pattern collection with a configuration layer on top. These are the best-known examples.

  • Singleton (as a scope). By default a bean is created once per container and shared. This is not the textbook static singleton: Spring manages the lifetime, so tests can still replace it. See Dependency Injection in Practice.
  • Factory and Abstract Factory. BeanFactory and ApplicationContext create objects from definitions. @Bean methods and FactoryBean classes are factory methods you write yourself.
  • Dependency Injection and Inversion of Control. The container builds your objects and passes their collaborators in; see Inversion of Control and IoC Containers.
  • Proxy. Annotations such as @Transactional, @Cacheable and @Async work because Spring wraps your bean in a proxy that begins the transaction, checks the cache or hands off to a thread before calling your method. A method called from inside the same class bypasses the proxy, which is a common surprise.
  • Template Method. JdbcTemplate, RestTemplate and TransactionTemplate own the boring steps (open, handle errors, close) and call your code for the interesting part.
  • Observer. ApplicationEventPublisher and @EventListener let one bean publish an event and others react.
  • Front Controller. DispatcherServlet receives every web request and routes it to a handler.
  • Strategy and Adapter. Pluggable pieces such as view resolvers and message converters are strategies, and HandlerAdapter lets differently shaped controllers be invoked uniformly.
  • Builder. ResponseEntity.ok().header(...).body(...), UriComponentsBuilder and RestClient.builder() are fluent builders.
  • Repository. Spring Data repositories implement the Repository pattern from just an interface.
Java
// Read-only: a Template Method style call. JdbcTemplate does the connection,
// statement, error translation and cleanup; you supply the SQL and a row mapper (a Strategy).
List<String> names = jdbcTemplate.query(
    "select name from customers where active = ?",
    (resultSet, rowNumber) -> resultSet.getString("name"),
    true);

The callback (resultSet, rowNumber) -> ... is a strategy plugged into a template. Two patterns in one call is normal; real designs mix them.

Using this knowledge

  • In interviews, give the pattern, the class, and one sentence on why it fits: "BufferedReader is a Decorator: it wraps a Reader, is itself a Reader, and adds buffering."
  • When reading unfamiliar code, look for the shape (a wrapper that implements the same interface, a callback list, a static creation method) before reading details.
  • When designing, copy the restraint. The JDK uses a pattern where it removes real duplication or coupling, and plain code everywhere else.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which pattern is new BufferedReader(new InputStreamReader(stream))?

    Each layer wraps another reader-like object, keeps the same abstraction and adds something, like decoding or buffering.
  2. 2. Why does Arrays.asList(array).set(0, "X") change the original array?

    Arrays.asList adapts the array to the List interface as a view, so writes go through.
  3. 3. You extend AbstractList and write only get and size. Which pattern makes contains and toString work?

    The base class owns the algorithms and calls the steps you implement, which is Template Method.
  4. 4. Why does a Spring @Transactional method called from another method of the same class often not start a transaction?

    The transaction is added by a proxy around the bean. An internal call goes straight to the object and never passes through the proxy.
  5. 5. Integer.valueOf(127) == Integer.valueOf(127) is true but the same test for 128 is false. Which pattern explains it?

    Integer keeps shared instances for -128 to 127. Larger values create new objects, so compare boxed numbers with equals.

Summary

  • The JDK and Spring are built from patterns: factories (List.of), builders (StringBuilder), decorators (I/O wrappers), adapters (Arrays.asList), flyweights (Integer cache), strategies (Comparator) and more.
  • AbstractList shows Template Method, Proxy and Spring's @Transactional show Proxy, and Runnable shows Command.
  • Spring adds scoped singletons, factories, dependency injection, proxies, template classes, events and a front controller.
  • Name the pattern by its intent: same interface plus extra behavior is a decorator; same interface plus control is a proxy.
  • Recognizing patterns in real code makes libraries easier to learn and gives you strong interview answers.

Next lesson: Design Pattern Interview Questions.