Skip to lesson

Structural patterns practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Five structural patterns wrap objects in similar ways, so they are easy to confuse and easy to get wrong. Can you tell them apart in new code and spot the three bugs that wrappers cause?

Recognising the five structural patterns

Example 1 builds one small checkout that uses all five patterns, and labels each wrapper with its pattern.

Example 1 · Five structural patterns in one small checkout

FivePatternsDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
interface NotificationService {    void send(String phone, String message);}
class LegacySmsApi {                                          // vendor class we cannot edit    void sendSms(String mobile, String text, int priority) {        System.out.println("  SMS(" + mobile + ", p" + priority + "): " + text);    }}
class SmsAdapter implements NotificationService {             // ADAPTER: different interface    private final LegacySmsApi api = new LegacySmsApi();
    public void send(String phone, String message) {        api.sendSms("+91" + phone, message, 1);    }}
class LoggingNotifier implements NotificationService {        // DECORATOR: same interface, adds    private final NotificationService inner;
    LoggingNotifier(NotificationService inner) {        this.inner = inner;    }
    public void send(String phone, String message) {        System.out.println("[log] sms to " + phone);        inner.send(phone, message);    }}
interface PriceLookup {    int priceOf(String sku);}
class CatalogDb implements PriceLookup {    public int priceOf(String sku) {        System.out.println("  db: price of " + sku);        return sku.equals("PEN-01") ? 20 : 240;    }}
class CachedPriceLookup implements PriceLookup {    private final PriceLookup real;    private final Map<String, Integer> cache = new HashMap<>();
    CachedPriceLookup(PriceLookup real) {        this.real = real;    }
    public int priceOf(String sku) {        return cache.computeIfAbsent(sku, real::priceOf);    }}
interface Sellable {    int price();}
class Item implements Sellable {    private final String sku;    private final PriceLookup prices;
    Item(String sku, PriceLookup prices) {        this.sku = sku;        this.prices = prices;    }
    public int price() {        return prices.priceOf(sku);    }}
class Bundle implements Sellable {    private final List<Sellable> parts = new ArrayList<>();
    Bundle add(Sellable s) {        parts.add(s);        return this;    }
    public int price() {        int sum = 0;        for (Sellable s : parts) sum += s.price();        return sum;    }}
class CheckoutFacade {    private final NotificationService notifier;
    CheckoutFacade(NotificationService notifier) {        this.notifier = notifier;    }
    void placeOrder(String phone, Sellable cart) {        int amount = cart.price();        notifier.send(phone, "Paid Rs " + amount);    }}
public class FivePatternsDemo {    public static void main(String[] args) {        PriceLookup prices = new CachedPriceLookup(new CatalogDb());        Sellable cart = new Bundle()                .add(new Item("PEN-01", prices))                .add(new Item("PEN-01", prices))                .add(new Bundle().add(new Item("NOTE-05", prices)));        new CheckoutFacade(new LoggingNotifier(new SmsAdapter())).placeOrder("9811100001", cart);    }}
Output
  db: price of PEN-01
  db: price of NOTE-05
[log] sms to 9811100001
  SMS(+919811100001, p1): Paid Rs 280

What this code does

  • Each wrapper is labelled with its pattern. The adapter and the decorator both implement NotificationService, but only the adapter holds a class with a different interface.
  • The pen's price is read from the database once: the second pen is a cache hit inside the proxy. The facade sees only one Sellable and one NotificationService.

In ShopLite, all five often meet in one flow: an adapter for the SMS vendor, a logging decorator around it, a caching proxy for prices, bundles as composites and a checkout facade in front.

Tell them apart by what the outer class offers and what it holds:

  • Adapter: a different interface from the one class it holds. Purpose: make it fit.
  • Decorator: the same interface as the one object it holds, and it always forwards. Purpose: add behaviour.
  • Proxy: the same interface, and it may not forward. Purpose: control access (lazy, security, cache).
  • Facade: a new, small interface over many classes. Composite: many children of its own interface in a tree.

Mistake: a decorator that forgets to delegate

Example 2 shows a decorator that logs and reports success but never calls inner, and the fixed version.

Example 2 · Mistake: the decorator never calls inner

ForgetDelegateDemo.javaJava
interface NotificationService {    boolean send(String phone, String message);}
class SmsService implements NotificationService {    public boolean send(String phone, String message) {        System.out.println("  SMS to " + phone + ": " + message);        return true;    }}
class BrokenLoggingNotifier implements NotificationService {    private final NotificationService inner;
    BrokenLoggingNotifier(NotificationService inner) {        this.inner = inner;    }
    public boolean send(String phone, String message) {        System.out.println("[log] sending to " + phone);        return true;                                   // bug: inner is never called    }}
class LoggingNotifier implements NotificationService {    private final NotificationService inner;
    LoggingNotifier(NotificationService inner) {        this.inner = inner;    }
    public boolean send(String phone, String message) {        System.out.println("[log] sending to " + phone);        boolean sent = inner.send(phone, message);      // delegate exactly once        System.out.println("[log] sent = " + sent);        return sent;    }}
public class ForgetDelegateDemo {    public static void main(String[] args) {        System.out.println("Broken:");        new BrokenLoggingNotifier(new SmsService()).send("9811100001", "OTP 4821");        System.out.println("Fixed:");        new LoggingNotifier(new SmsService()).send("9811100001", "OTP 4821");    }}
Output
Broken:
[log] sending to 9811100001
Fixed:
[log] sending to 9811100001
  SMS to 9811100001: OTP 4821
[log] sent = true

What this code does

  • The broken decorator logs and reports success, but no SMS line appears: the customer never gets the OTP, and nothing in the logs says so.
  • The fixed version stores the result of one inner.send call and uses it for both the log line and the return value.

A decorator's whole contract is "do my extra work, then call inner". If it returns its own result instead, the chain is cut: the real object never runs, yet everything above it looks fine. The opposite slip, calling inner twice (once to log, once to return), sends an SMS or charges a card twice.

The rule: call inner exactly once, keep the result in a variable, and use that variable everywhere after it.

Find the bug

Find the wrapper bug

Each snippet has one wrong line. Click it.

Every call sends the SMS twice.

Round 1 of 2

Mistake: an adapter that leaks the adaptee

Example 3 wraps a legacy SMS API in a clean adapter. Callers pass a plain 10-digit number and never see the vendor's details.

Example 3 · An adapter for a legacy SMS API, done properly

LegacySmsAdapterDemo.javaJava
interface NotificationService {    void send(String phone, String message);}
class NotificationFailedException extends RuntimeException {    NotificationFailedException(String message, Throwable cause) {        super(message, cause);    }}
class SmsGatewayException extends Exception {                 // vendor's checked exception    SmsGatewayException(String message) {        super(message);    }}
class LegacySmsApi {    int sendSms(String mobileWith91, String text, int priority) throws SmsGatewayException {        if (text.length() > 40) {            throw new SmsGatewayException("E22 message too long");        }        System.out.println("  vendor: " + mobileWith91 + " p" + priority + " '" + text + "'");        return 200;    }}
class LegacySmsAdapter implements NotificationService {    private final LegacySmsApi api;                             // held privately, never exposed
    LegacySmsAdapter(LegacySmsApi api) {        this.api = api;    }
    @Override    public void send(String phone, String message) {        try {            api.sendSms("+91" + phone, message, 1);             // format converted here only        } catch (SmsGatewayException e) {            throw new NotificationFailedException("SMS not sent to " + phone, e);        }    }}
public class LegacySmsAdapterDemo {    public static void main(String[] args) {        NotificationService sms = new LegacySmsAdapter(new LegacySmsApi());        sms.send("9811100001", "Order A101 shipped");        try {            sms.send("9811100002", "Your order A102 is out for delivery today");        } catch (NotificationFailedException e) {            System.out.println(e.getMessage() + " (cause: " + e.getCause().getMessage() + ")");        }    }}
Output
  vendor: +919811100001 p1 'Order A101 shipped'
SMS not sent to 9811100002 (cause: E22 message too long)

What this code does

  • Callers pass a plain 10-digit number and never see +91, priorities or SmsGatewayException. If the vendor changes, only LegacySmsAdapter changes.
  • The vendor's checked exception becomes ShopLite's unchecked NotificationFailedException, with the original kept as the cause for the logs.

An adapter fails at its job when the vendor's details escape: callers still add the +91 prefix themselves, still catch the vendor's exception, or the adapter extends the vendor class so its methods are public on the adapter.

A clean adapter implements your interface, holds the vendor object privately, converts every format in one place and turns vendor errors into your own exception with the original as the cause.

Fix the error

Fix the leaky adapter

The vendor method throws a checked exception. Pick the replacement for the highlighted line.

Callers of send must not see the vendor exception.

public void send(String phone, String msg) {
api.sendSms("+91" + phone, msg, 1);
}

Error

error: unreported exception SmsGatewayException; must be caught or declared to be thrown

Tracing a stacked decorator chain

Example 4 stacks three decorators, A, B and C, that each print a line before and after the call and add a tag to the message.

Example 4 · Tracing a three-layer chain

ChainTraceDemo.javaJava
interface NotificationService {    void send(String message);}
class Sms implements NotificationService {    public void send(String message) {        System.out.println("    SMS: " + message);    }}
class Tag implements NotificationService {    private final String name;    private final NotificationService inner;
    Tag(String name, NotificationService inner) {        this.name = name;        this.inner = inner;    }
    public void send(String message) {        System.out.println(name + " before: " + message);        inner.send(message + " #" + name);                  // each layer changes the text        System.out.println(name + " after");    }}
public class ChainTraceDemo {    public static void main(String[] args) {        NotificationService chain = new Tag("A", new Tag("B", new Tag("C", new Sms())));        chain.send("hi");    }}
Output
A before: hi
B before: hi #A
C before: hi #A #B
    SMS: hi #A #B #C
C after
B after
A after

What this code does

  • "before" lines run A, B, C (outside in) and "after" lines run C, B, A (inside out), like a stack of plates.
  • Each layer passes on the text it received plus its own tag, so the SMS shows the tags in the order A, B, C.

To trace a chain, read the constructor calls from the outside in: the outermost decorator runs its "before" part first. The call then goes inward to the real object, and the "after" parts run from the inside out.

Write the chain as a column on paper, with "before" lines going down and "after" lines coming back up. Changes to the message also follow this order: an inner decorator sees what the outer ones already changed.

Predict the output

Trace the chain

Upper capitalises the message. Sign appends " -s". ConsoleNotifier prints SMS: <message>.

Round 1 of 2

Upper is the outer layer.

NotificationService n = new Upper(new Sign(new ConsoleNotifier()));
n.send("98111", "hi");

Finish up

Mark complete & continue

Next: Project: ShopLite checkout facade