00:00

Structural Design Patterns in Java

Last updated:

Structural design patterns in Java are proven ways to combine classes and objects into larger structures while keeping those structures flexible. They show how to wrap, adapt, group and simplify objects, so that incompatible parts fit together, features can be layered on, and complex subsystems get a simple entry point.

They matter because real applications are assembled from parts that were not designed together: vendor SDKs, legacy modules, shared services and cross-cutting concerns such as caching and logging. Without a plan, that glue code ends up copied into controllers and services. Structural patterns give the glue a shape. They are one of the three Gang of Four (GoF) categories, together with creational and behavioral patterns.

1. What Are Structural Design Patterns?

The GoF book describes structural patterns as being concerned with how classes and objects are composed to form larger structures.

In everyday terms, they answer: how do these pieces fit together? Most of them place one object in front of, around or above others: an adapter in front of a vendor SDK, a decorator around a service, a facade above a subsystem, a composite above a tree of children. The client keeps talking to a simple, stable interface while the structure behind it changes.

Two flavours exist. Class structural patterns use inheritance to combine interfaces, as a class adapter does. Object structural patterns, the vast majority, use composition: one object holds a reference to another and delegates to it. Composition is why these patterns can be rearranged at runtime, and why they follow "favour composition over inheritance", the Open/Closed Principle and the Interface Segregation Principle.

2. The 7 Structural Patterns at a Glance

PatternIn one sentenceTypical Java example
AdapterConvert one interface into the one a client expects.InputStreamReader, Arrays.asList()
BridgeSplit an abstraction from its implementation so both can vary.JDBC API over vendor drivers
CompositeTreat single objects and groups of objects the same way.AWT Container holding Components
DecoratorAdd behaviour by wrapping an object with the same interface.BufferedInputStream, Collections.synchronizedList()
FacadeGive a complex subsystem one simple entry point.SLF4J, Spring's JdbcTemplate
FlyweightShare immutable objects to save memory.Integer.valueOf() cache, string pool
ProxyControl access to an object with a same-interface stand-in.java.lang.reflect.Proxy, Spring AOP proxies

Each pattern has its own tutorial on JavaByTechie with three runnable examples and interview questions.

3. When Are Structural Patterns Useful?

  • Integrating code you do not own: a pricing SDK that returns paise through an unfamiliar method name.
  • Adding cross-cutting behaviour: caching, logging, retries or security around a service without editing it.
  • Simplifying or organising: one call for a product page that needs price, stock and reviews, or one tree for nested bundles.

4. UML Class Diagram

A whole category has no single diagram, so this one shows four structural patterns working together in the product-page code from section 8.

Structural patterns in one product page ProductPageFacade uses PriceService, StockService and ReviewService. LoggingPriceDecorator, CachingPriceProxy and LegacyPricingAdapter implement PriceService. The decorator and the proxy each wrap another PriceService, and the adapter wraps LegacyPricingSdk. Facade ProductPageFacade + productCard(sku): String StockService ReviewService «interface» PriceService + priceOf(sku): BigDecimal implements Decorator LoggingPriceDecorator - inner: PriceService Proxy CachingPriceProxy - target: PriceService Adapter LegacyPricingAdapter - sdk both wrap another PriceService LegacyPricingSdk + fetchPaise(sku): long
Four structural patterns in one product page: an adapter in front of the vendor SDK, a caching proxy and a logging decorator around it, and a facade above everything.
  1. Adapter: LegacyPricingAdapter implements PriceService and holds the SDK, translating paise into rupees.
  2. Proxy: CachingPriceProxy implements the same interface and wraps another PriceService, answering from a cache when it can.
  3. Decorator: LoggingPriceDecorator also implements and wraps PriceService, adding logging and always delegating.
  4. Facade: ProductPageFacade depends on the interface and two other services, and offers one method to the page.

5. Step-by-Step Execution Flow

  1. At startup the wiring code builds the stack: adapter around the SDK, proxy around the adapter, decorator around the proxy, and passes the decorator to the facade.
  2. The page calls facade.productCard("SKU-TV").
  3. The facade calls priceOf(); the decorator logs and forwards to the proxy.
  4. On the first call the proxy's cache is empty, so it asks the adapter, which calls fetchPaise() and converts the result.
  5. The facade adds stock and rating data and returns one string.
  6. On the second call, the proxy answers from its cache: the SDK is not called again.

6. Real-World Use Cases

  • E-commerce: adapters for supplier feeds, nested product bundles as composites, caching proxies for prices and BFF facades for mobile screens.
  • Payments and banking: one adapter per gateway, decorators for fraud checks and auditing, Bridge to keep payment types independent of payment rails.
  • Notifications: adapters for SMS and email vendors, decorators for masking, flyweights for compiled templates.
  • The JDK: the java.io stream classes (Decorator), InputStreamReader (Adapter), java.lang.reflect.Proxy, the Integer cache (Flyweight) and AWT Container (Composite).
  • Spring: @Transactional and @Cacheable work through proxies, Spring MVC calls handlers through HandlerAdapters, JdbcTemplate acts as a facade over JDBC, and CompositePropertySource and CompositeCacheManager are composites.

7. Problem Without Structural Patterns

A product-page controller that talks to the vendor SDK directly:

ProductPageWithoutStructuralPatterns.java
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class ProductPageWithoutStructuralPatterns {

    // Vendor SDK: slow, and prices come back in paise
    static final class LegacyPricingSdk {
        int calls = 0;
        long fetchPaise(String sku) {
            calls++;
            return sku.equals("SKU-TV") ? 4_299_900 : 129_900;
        }
    }

    static final class StockService { int unitsLeft(String sku) { return sku.equals("SKU-TV") ? 3 : 40; } }
    static final class ReviewService { double rating(String sku) { return sku.equals("SKU-TV") ? 4.4 : 4.1; } }

    // The page controller converts units, caches, logs and combines three services by hand
    static final class ProductPageController {
        private final LegacyPricingSdk sdk = new LegacyPricingSdk();
        private final StockService stock = new StockService();
        private final ReviewService reviews = new ReviewService();

        String productCard(String sku) {
            System.out.println("  [log] price lookup " + sku);
            BigDecimal price = BigDecimal.valueOf(sdk.fetchPaise(sku), 2);     // unit conversion in UI code
            return sku + ": Rs. " + price + ", " + stock.unitsLeft(sku) + " left, rated " + reviews.rating(sku);
        }

        // The search page needed caching, so it got its own copy of the lookup
        private final Map<String, BigDecimal> searchCache = new HashMap<>();
        BigDecimal searchPrice(String sku) {
            return searchCache.computeIfAbsent(sku, s -> BigDecimal.valueOf(sdk.fetchPaise(s), 2));
        }
    }

    public static void main(String[] args) {
        ProductPageController page = new ProductPageController();
        System.out.println(page.productCard("SKU-TV"));
        System.out.println(page.productCard("SKU-TV"));
        System.out.println("search shows Rs. " + page.searchPrice("SKU-TV"));
        System.out.println("SDK calls: " + page.sdk.calls);
    }
}
Console
  [log] price lookup SKU-TV
SKU-TV: Rs. 42999.00, 3 left, rated 4.4
  [log] price lookup SKU-TV
SKU-TV: Rs. 42999.00, 3 left, rated 4.4
search shows Rs. 42999.00
SDK calls: 3
  • Vendor details leak: paise conversion lives in UI code, and every caller repeats it.
  • Duplicated cross-cutting code: logging is inline, and the search page grew its own separate cache.
  • Wasted calls: three SDK calls for the same price.
  • Tight coupling: the controller depends on four concrete classes.

8. Structural Design Patterns in Java: The Solution

Give each concern a structural pattern: an Adapter hides the SDK behind PriceService, a Proxy adds one shared cache, a Decorator adds logging, and a Facade gives the page one method.

StructuralPatternsTogether.java
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StructuralPatternsTogether {

    // Vendor SDK we cannot change: prices in paise, different method name
    static final class LegacyPricingSdk {
        int calls = 0;
        long fetchPaise(String sku) {
            calls++;
            return sku.equals("SKU-TV") ? 4_299_900 : 129_900;
        }
    }

    // The interface our application wants
    interface PriceService {
        BigDecimal priceOf(String sku);
    }

    // Adapter: makes the SDK look like a PriceService
    static final class LegacyPricingAdapter implements PriceService {
        private final LegacyPricingSdk sdk;
        LegacyPricingAdapter(LegacyPricingSdk sdk) { this.sdk = sdk; }
        public BigDecimal priceOf(String sku) { return BigDecimal.valueOf(sdk.fetchPaise(sku), 2); }   // paise -> rupees
    }

    // Proxy: controls access to the slow service by answering from a cache when it can
    static final class CachingPriceProxy implements PriceService {
        private final PriceService target;
        private final Map<String, BigDecimal> cache = new ConcurrentHashMap<>();
        CachingPriceProxy(PriceService target) { this.target = target; }
        public BigDecimal priceOf(String sku) { return cache.computeIfAbsent(sku, target::priceOf); }
    }

    // Decorator: adds logging and always delegates
    static final class LoggingPriceDecorator implements PriceService {
        private final PriceService inner;
        LoggingPriceDecorator(PriceService inner) { this.inner = inner; }
        public BigDecimal priceOf(String sku) {
            System.out.println("  [log] price lookup " + sku);
            return inner.priceOf(sku);
        }
    }

    static final class StockService { int unitsLeft(String sku) { return sku.equals("SKU-TV") ? 3 : 40; } }
    static final class ReviewService { double rating(String sku) { return sku.equals("SKU-TV") ? 4.4 : 4.1; } }

    // Facade: one simple call for the product card, over three services
    static final class ProductPageFacade {
        private final PriceService prices;
        private final StockService stock;
        private final ReviewService reviews;

        ProductPageFacade(PriceService prices, StockService stock, ReviewService reviews) {
            this.prices = prices;
            this.stock = stock;
            this.reviews = reviews;
        }

        String productCard(String sku) {
            return sku + ": Rs. " + prices.priceOf(sku) + ", " + stock.unitsLeft(sku) + " left, rated " + reviews.rating(sku);
        }
    }

    public static void main(String[] args) {
        LegacyPricingSdk sdk = new LegacyPricingSdk();
        PriceService shared = new CachingPriceProxy(new LegacyPricingAdapter(sdk));   // one cached price source
        PriceService logged = new LoggingPriceDecorator(shared);                     // logging layered on top

        ProductPageFacade page = new ProductPageFacade(logged, new StockService(), new ReviewService());
        System.out.println(page.productCard("SKU-TV"));
        System.out.println(page.productCard("SKU-TV"));
        System.out.println("search shows Rs. " + shared.priceOf("SKU-TV"));       // search reuses the same cache
        System.out.println("SDK calls: " + sdk.calls);
    }
}
Console
  [log] price lookup SKU-TV
SKU-TV: Rs. 42999.00, 3 left, rated 4.4
  [log] price lookup SKU-TV
SKU-TV: Rs. 42999.00, 3 left, rated 4.4
search shows Rs. 42999.00
SDK calls: 1

The page output is identical, but the SDK is called once instead of three times, because product and search pages share one caching proxy. Unit conversion lives in the adapter only, logging can be removed by taking one wrapper out of the stack, and the page depends on a facade and an interface instead of four concrete classes. The program runs on Java 21 with java StructuralPatternsTogether.java.

9. Best Practices and Common Mistakes

Best practices

  • Design the interface around your domain, and let adapters translate to vendors.
  • Keep each wrapper to one job, and assemble stacks in one place, such as a configuration class.
  • Prefer object composition to inheritance, so wrappers can be reordered or removed.
  • Thread safety: wrappers are usually shared. Keep them stateless, or use concurrent structures for caches and counters, as the proxy's ConcurrentHashMap does; flyweights must be immutable.

Common mistakes

  • Leaky adapters that return vendor types.
  • God facades that grow to cover every feature.
  • Ignoring wrapper order: logging outside the cache logs every call, logging inside it logs only misses.
  • Overengineering: wrapping a class whose interface already fits and will never change.

10. When to Use and When Not to Use

Use them at system boundaries, when you integrate third-party code, when the same concern is being copied into many callers, or when a subsystem has become hard for clients to use correctly.

Avoid them when you own both sides and can simply change an interface, when there is only one caller and one implementation, or when a framework already provides the wrapper, such as Spring's @Cacheable instead of a hand-written caching proxy.

11. Advantages and Disadvantages

Advantages

  • Reuse of existing code without modifying it.
  • Loose coupling through stable interfaces.
  • Composable features that can be stacked and reordered.
  • Simpler clients and, with Flyweight, lower memory use.

Disadvantages

  • More classes and layers to read.
  • Harder debugging through stacks of wrappers.
  • Order-sensitive behaviour when several wrappers are combined.

12. Comparison of the Wrapper Patterns

Four structural patterns wrap another object, which makes them easy to confuse in interviews. Their intent tells them apart:

AspectAdapterDecoratorProxyFacade
IntentChange an interfaceAdd behaviourControl accessSimplify a subsystem
Interface exposedDifferent from the wrapped objectSameSameNew and simpler
WrapsOne adapteeOne component, stackableOne subjectMany objects
May skip the real callNoRarelyYes: cache, security, lazinessNot applicable

Bridge also looks like a wrapper, but it is designed up front to let two hierarchies vary independently. Composite and Flyweight are about structure and sharing rather than wrapping. Compared with the other categories, structural patterns deal with combining objects; creational patterns deal with making them, and behavioral patterns with how they interact.

13. Summary

  • Structural design patterns in Java define how classes and objects are combined into larger, flexible structures.
  • Purpose: integrate, extend and simplify without editing existing code.
  • The seven GoF patterns are Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy.
  • Most work by composition: one object holds another and delegates to it.
  • Used for vendor integration, caching, logging, trees, simplified APIs and memory savings.
  • Benefits: reuse, loose coupling and composable features.
  • Choose by intent, mind wrapper order, and keep shared wrappers thread-safe.

14. Java Design Pattern Interview Questions and Answers

Q1. What is the difference between class and object structural patterns?

Class structural patterns use inheritance to combine interfaces or implementations; the class adapter is the standard example. Object structural patterns use composition: an object holds another and delegates to it. Object patterns can be changed at runtime and are far more common in Java because of single inheritance.

Q2. Why do most structural patterns prefer composition over inheritance?

Composition lets you choose and combine collaborators at runtime, works with final classes, and avoids a subclass for every combination of features. Inheritance fixes the relationship at compile time and exposes the parent's internals to the child.

Q3. Decorator and Proxy have the same structure. How do you tell them apart?

By intent and control. A decorator adds behaviour and always passes the call on; decorators are usually stacked by the client. A proxy controls access: it may answer from a cache, refuse the call or create the real object lazily, and it is often created by a framework without the client knowing.

Q4. Adapter or Facade: how do you decide?

Use an Adapter when one existing interface has the wrong shape for your client, keeping roughly the same functionality. Use a Facade when a whole subsystem is too complicated to use directly and clients need a few simple, task-level methods.

Q5. What is the difference between an object adapter and a class adapter in Java?

An object adapter holds the adaptee in a field and works with any subclass of it. A class adapter extends the adaptee and implements the target interface, so it cannot be used when the adaptee is final and ties you to one concrete class. Object adapters are the usual choice in Java.

class SdkAdapter implements PriceService {        // object adapter
    private final LegacyPricingSdk sdk;
    SdkAdapter(LegacyPricingSdk sdk) { this.sdk = sdk; }
    public BigDecimal priceOf(String sku) { return BigDecimal.valueOf(sdk.fetchPaise(sku), 2); }
}
Q6. Where does the JDK use the Decorator pattern?

Throughout java.io: BufferedInputStream, DataInputStream and GZIPInputStream extend FilterInputStream and wrap another InputStream; readers and writers follow the same design. Collections.unmodifiableList() and synchronizedList() also wrap a collection with the same interface.

Q7. How do Spring's @Transactional and @Cacheable relate to structural patterns?

Spring wraps the bean in a proxy, a JDK dynamic proxy for interfaces or a CGLIB subclass for classes, and Spring Boot uses CGLIB by default. The proxy starts the transaction or checks the cache, then calls your method. Calls from inside the same bean do not pass through the proxy, which is why self-invocation skips these annotations.

Q8. When is Bridge better than inheritance?

When a class varies in two independent dimensions, such as payment type and payment rail. Inheritance needs a subclass for every combination (m × n), while Bridge needs one class per variant on each side (m + n) and lets you choose the pairing at runtime.

Q9. What makes the Composite pattern "transparent" or "safe"?

In the transparent version, child-management methods such as add() are declared on the shared component interface, so clients treat leaves and groups identically but leaves must reject them. In the safe version, only composites have those methods, so misuse fails at compile time. Most modern Java code chooses safety, often with sealed interfaces.

Q10. Why must flyweights be immutable?

A flyweight is shared by many users at once. If one user changes it, every other user sees the change, which corrupts their data, and concurrent changes create race conditions. Immutable flyweights can be shared freely across threads.

Q11. Why does Integer.valueOf(127) == Integer.valueOf(127) return true, but not for 128?

Integer.valueOf() is a flyweight factory that caches values from -128 to 127 by default, so those calls return the same object. Larger values create new objects, so == compares different references. Always compare wrapper values with equals().

Q12. Logging is placed inside a caching proxy in one service and outside it in another. What is the difference?

Wrappers run in the order they are nested. Logging outside the cache records every request, including cache hits; logging inside it records only the calls that reach the real service, which tells you about misses and load on the dependency. Choose deliberately and document the order.

Q13. How do you decorate an interface with many methods without forwarding each one by hand?

Write the forwarding once in an abstract base decorator, as FilterInputStream does, and let concrete decorators override only what they change. Alternatives are a JDK dynamic proxy that intercepts selected methods, or splitting a large interface into smaller ones.

Q14. How does an API gateway or BFF relate to structural patterns?

A Backend for Frontend is a Facade at the network level: it aggregates several microservice calls into one response shaped for a client. A gateway also acts as a Proxy, adding authentication, rate limiting and routing in front of services.

Q15. What is an anti-corruption layer, and how is it built?

In Domain-Driven Design, an anti-corruption layer stops another system's model from leaking into your domain. It is usually built from adapters and translators, sometimes behind a facade, so your code only sees its own types.

Q16. What are the limitations of JDK dynamic proxies?

java.lang.reflect.Proxy can only implement interfaces, so the target must have one and callers must use it. Every call goes through reflection in an InvocationHandler, and exceptions arrive wrapped in InvocationTargetException that the handler should unwrap. Class-based proxies such as CGLIB or ByteBuddy remove the interface requirement but cannot intercept final methods.

Q17. Two threads call a caching proxy for the same missing key at the same time. What can go wrong?

With a naive "check, then put", both threads miss and both call the slow service, a cache stampede. ConcurrentHashMap.computeIfAbsent() loads each key at most once while other threads wait. For production caches, a library such as Caffeine adds expiry and size limits too.

Q18. A facade in your codebase has grown to 40 methods. What do you do?

Split it by use case or bounded context, for example a checkout facade, a returns facade and an order-query facade. Facades may share the same underlying services, so splitting is cheap and each facade stays focused.

Q19. How do structural patterns help with testing?

Because clients depend on interfaces, tests can swap in fakes: a fake price service instead of the vendor adapter, or a facade built from stubs. Wrappers can also be tested on their own by giving them a fake inner object and checking what they add.

Q20. How would you explain structural patterns in one minute in an interview?

Say they are about fitting objects together: Adapter fixes interface mismatches, Facade simplifies, Decorator adds features, Proxy controls access, Composite builds trees, Bridge separates two dimensions, and Flyweight shares state. Then give one real example, such as Spring's transactional proxies or java.io decorators, and mention the cost: more layers to debug.