Java Decorator and Proxy Patterns: Add Behavior Without Changing Classes

Maya's bookstore now sends order confirmations by email, and the shop has two new requirements. First, every confirmation must be logged — so the support desk can answer "did the email go out?" — and retried when the mail server is busy, instead of lost. Second, the shop's price list lives behind a document service: anyone may read it, only an editor may change it. The catch: the sender and the document service already work, and nobody wants to rewrite either class — or paste the same logging, retry, and access check into every caller.

Post 1 asked what varies? Post 2, Java Singleton Pattern: Enum, Lazy Holder & Double-Checked Locking Explained, asked how many? Post 3, Java Factory Pattern: Factory Method vs Abstract Factory With Examples, asked who decides which object gets created? Post 4, Java Builder Pattern: Build Complex Objects Without Telescoping Constructors, asked how do you assemble one object, piece by piece? Post 5, Java Adapter and Facade Patterns: Integrate Incompatible Code Cleanly, asked how do you use an interface you cannot change — and hide a whole subsystem behind one call? This post asks a sixth question: how do you add behavior to an object without changing its class — and how do you guard one without touching it? The answer is two patterns that work as a pair: Decorator and Proxy. The principle for this lesson: Prefer wrapping to subclassing when the behavior, not the type, is what varies.

1. The customer problem

Maya's requirement is plain: every confirmation must be logged and retried when the mail server is busy, and the price list must be readable by anyone but changeable only by an editor — without rewriting the sender or the document service, or pasting the same checks into every caller. One interface per job, the extra behavior added around them, not inside them.

She asked for two properties: the sending behavior must be addable and removable per caller, and the write rule must be enforced in exactly one place. The test for this post is simple: add logging to one caller without touching the sender, add a retry without touching the logger, and change who may write without touching the document service.

2. Clarify the ask: what varies, what stays

Before writing any code, split the problem again:

  • What stays stable: the two interfaces — Notifier with one method, send, and DocumentService with read and write — and the message itself. Every caller already uses them, and they will not change.
  • What varies: what happens around a send — logging it, retrying it, in which order — and who may write a document. The behavior varies per caller and per role; the object does not.

Section 5 shows what happens without that split: logging pasted into the sender, a retry loop pasted into every caller, an access check pasted into every write call site — three copies of each rule, drifting apart.

3. The minimum concept: add behavior by wrapping

Two patterns, two questions — learn them apart, then watch them compose.

The Decorator answers: how do you add behavior to an object without changing its class? Four parts, each with one job:

  • The component — the interface the client uses, Notifier. One method, send.
  • The concrete component — EmailNotifier, the object that actually sends the message.
  • The decorator — LoggingNotifier or RetryNotifier: same interface, another Notifier inside, behavior added around the call.
  • The client — the checkout code, which calls send, unaware of the layers.

The Proxy answers: how do you control access to an object without changing it? Four parts too:

  • The subject — the interface the client uses, DocumentService.
  • The real subject — RealDocumentService, the object that actually reads and writes documents.
  • The proxy — AccessProxy: same interface, the real service inside, a role check before the call.
  • The client — the shop code, which uses the proxy as if it were the service, never receiving the real object.

The difference is worth naming precisely. A decorator adds behavior the client wants — logging, retrying — and the client usually knows the layers are there, because it built them. A proxy controls behavior the client may not want to think about — access, cost — and the client often does not know it is there, because it was handed the proxy in place of the real thing. Both keep the interface exactly as it is — unlike post 5's adapter, which changes an interface so two things fit. An observer, which post 7 takes up, announces a change instead of wrapping a call.

Decorator layers vs proxy gatekeeper DECORATOR PROXY Client LoggingNotifier.send() RetryNotifier.send() EmailNotifier.send() Same interface at every layer; behavior added, not inherited. Client AccessProxy: checks the role RealDocumentService Viewer: read only. Editor: read and write. One gatekeeper — the real service stays hidden.

4. Build: one interface, two wrappers, one gatekeeper

Start with what stays stable — the interface, and the object that sends:

// The interface every caller programs against: one method, one message.
interface Notifier {
    void send(String message);
}

// The real sender. It writes the message to the outbox log.
final class EmailNotifier implements Notifier {
    public void send(String message) {
        System.out.println("sent: " + message);
    }
}

The mail service is flaky — busy twice, then fine — so the demo uses a stand-in that fails twice, then succeeds. Two failure types keep the retry honest: transient is worth retrying, permanent is not, and the code — not a comment — says which is which:

// Worth retrying: busy server, not a bad message.
final class TransientFailure extends RuntimeException {
    TransientFailure(String message) {
        super(message);
    }
}

// Unfixable by retrying: bad address, empty message.
final class PermanentFailure extends RuntimeException {
    PermanentFailure(String message) {
        super(message);
    }
}

// A mail service that is busy twice, then recovers.
final class FlakyNotifier implements Notifier {
    private int attempts;

    public void send(String message) {
        attempts++;
        if (attempts <= 2) {
            throw new TransientFailure("mail server busy");
        }
        System.out.println("sent: " + message);
    }

    int attempts() {
        return attempts;
    }
}

Now the first decorator: same interface, another Notifier inside, behavior added around the passed-through call — logging before and after:

// Logging around the send, passed through. If the send throws,
// no "sent ok" appears — that is how the log shows a failure.
final class LoggingNotifier implements Notifier {
    private final Notifier wrapped;

    LoggingNotifier(Notifier wrapped) {
        this.wrapped = wrapped;
    }

    public void send(String message) {
        System.out.println("sending: " + message);
        wrapped.send(message);
        System.out.println("sent ok: " + message);
    }
}

The second decorator retries a transient failure, up to three times, then gives up by throwing — saying nothing while it retries. Section 5 shows why that silence matters:

// First version: up to three attempts, then give up. Silent — section 5 shows why.
final class RetryNotifier implements Notifier {
    private final Notifier wrapped;

    RetryNotifier(Notifier wrapped) {
        this.wrapped = wrapped;
    }

    public void send(String message) {
        for (int attempt = 1; attempt <= 3; attempt++) {
            try {
                wrapped.send(message);
                return;
            } catch (TransientFailure e) {
                // try again
            }
        }
        throw new TransientFailure("gave up after 3 attempts");
    }
}

The whole thing working, end to end:

public class DecoratorDemo {
    public static void main(String[] args) {
        Notifier notifier = new LoggingNotifier(
                new RetryNotifier(new FlakyNotifier()));
        notifier.send("Order shipped");
    }
}
sending: Order shipped
sent: Order shipped
sent ok: Order shipped

Read that client code out loud: it names the message and gets it sent — no logging code, no retry loop, no failure counting. But the mail server was busy twice, and the log shows no trace of either failure. That silence is the first hole, and section 5 opens it up.

Now the proxy: two operations, and simple roles — a viewer may read, only an editor may write:

interface DocumentService {
    String read(String documentId);
    void write(String documentId, String text);
}

final class RealDocumentService implements DocumentService {
    public String read(String documentId) {
        return "contents of " + documentId;
    }

    public void write(String documentId, String text) {
        System.out.println("wrote " + documentId + ": " + text);
    }
}

// Roles in this shop: a viewer may read, only an editor may write.
enum Role {
    VIEWER, EDITOR
}

The proxy implements the same interface, holds the real service inside, and checks the role before passing a write through. Two details make it a proxy: the client receives the proxy instead of the real service, with no way to reach the real one — no getter, no field access. This first version denies the roles it knows about — section 6 shows why that is the wrong way round:

// The proxy: checks the role, then passes the call through.
final class AccessProxy implements DocumentService {
    private final DocumentService real;
    private final Role role;

    AccessProxy(DocumentService real, Role role) {
        this.real = real;
        this.role = role;
    }

    public String read(String documentId) {
        return real.read(documentId);
    }

    public void write(String documentId, String text) {
        if (role == Role.VIEWER) {
            throw new SecurityException("write requires the editor role");
        }
        real.write(documentId, text);
    }
}

A viewer reads the price list and is refused the write — an exception, not a silent no-op. Section 6 puts the proxy through its checks.

5. Break it: the retry that lied, the message sent three times, and the notification that vanished

The first version works. Working is not the same as correct — and this version has three holes.

The first hole is the order of the layers: the same three objects, wrapped differently, produce a different log — and one hides the truth. Order A is the shop's starting order, logging outside the retry; order B swaps them:

// Order A: logging outside the retry — the order the shop started with.
Notifier orderA = new LoggingNotifier(new RetryNotifier(new FlakyNotifier()));

// Order B: retry outside the logging — the same three objects, swapped.
Notifier orderB = new RetryNotifier(new LoggingNotifier(new FlakyNotifier()));
sending: Order shipped
sent: Order shipped
sent ok: Order shipped
sending: Order shipped
sending: Order shipped
sending: Order shipped
sent: Order shipped
sent ok: Order shipped

The first output is order A, the second order B — same message, same server, same three objects. In order A the log shows one send: the logging decorator only ever sees one call, the retry's single call from its point of view. The two failed attempts happened inside the retry, where the logging cannot see them. In order B the logging sits inside the retry, runs once per attempt, and the log shows all three. When the server stays down, order A's log shows one "sending:" line and then nothing — while order B shows each attempt as it happened.

A retry that gives up quietly returns normally after the last attempt, as if the message had been sent — and the logging outside it believes the lie:

// The same retry, minus its last line — it returns normally,
// as if the message had been sent.
for (int attempt = 1; attempt <= 3; attempt++) {
    try {
        wrapped.send(message);
        return;
    } catch (TransientFailure e) {
        // try again
    }
}
// gave up — and said nothing

// Busy every time, not just twice.
final class AlwaysBusyNotifier implements Notifier {
    private int calls;

    public void send(String message) {
        calls++;
        throw new TransientFailure("mail server busy");
    }

    int calls() {
        return calls;
    }
}
sending: Order shipped
sent ok: Order shipped

Read that output again: "sending", then "sent ok" — and nothing was sent. The server was busy three times, the retry gave up, and the log records a success that never happened. Nobody knows anything is wrong until the customer complains. A retry that swallows its final failure turns a visible error into an invisible one.

The second hole is what the retry retries: this sender transmits the message before it fails, waiting for the receipt:

// Transmits the message, then fails waiting for the receipt.
final class HalfSentNotifier implements Notifier {
    private int copies;

    public void send(String message) {
        copies++;
        System.out.println("transmitted: " + message + " (copy " + copies + ")");
        throw new TransientFailure("receipt lost");
    }
}
transmitted: Order shipped (copy 1)
transmitted: Order shipped (copy 2)
transmitted: Order shipped (copy 3)

Three copies of the same confirmation — and then the retry throws, so the caller sees a failure while the customer sees three emails. The retry did exactly what it was told, and what it was told was wrong: it retried a send that had already gone out. A failure that happens after the work is done is not transient in the sense a retry needs — retrying it duplicates the work instead of recovering it. The same carelessness retries what can never succeed: a sender that throws PermanentFailure for an unknown address is retried three times by a retry that catches RuntimeException instead of TransientFailure — three wasted calls. The unbounded form is a while (true) loop with no counter and no bound: run it against a down server and the thread that confirms the order never comes back.

The third hole is the smallest, and the easiest to miss in review: a decorator that forgets to delegate compiles, runs, and silently drops the work:

// A decorator that logs the message and forgets to pass it on.
final class SilentNotifier implements Notifier {
    private final Notifier wrapped;

    SilentNotifier(Notifier wrapped) {
        this.wrapped = wrapped;
    }

    public void send(String message) {
        System.out.println("logged: " + message);
        // forgot: wrapped.send(message);
    }
}
logged: Order shipped

That is the whole output. No "sent:", no exception, no error anywhere — the notification never left the shop, and nothing in the log says so. The compiler cannot catch it: the method is a perfectly valid implementation of the interface. A decorator's one job is to pass the call through — and this one is missing a single line.

6. Harden it: bounded retries, transient only, order on the record

The fix shape is the same every time: the implied rule, now written where the code can enforce it. First, the retry: transient failures only — the exception type, not a comment, decides — a named number of attempts, and a throw instead of a pretended success when it gives up:

// The retry, rewritten: bounded, transient-only.
final class RetryNotifier implements Notifier {
    // Most attempts: three, not thirty.
    static final int MAX_ATTEMPTS = 3;

    private final Notifier wrapped;

    RetryNotifier(Notifier wrapped) {
        this.wrapped = wrapped;
    }

    public void send(String message) {
        for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
            try {
                wrapped.send(message);
                return;
            } catch (TransientFailure e) {
                if (attempt == MAX_ATTEMPTS) {
                    throw e;
                }
                // Otherwise, try again — the logging layer records the attempt.
            }
        }
    }
}

Three things to notice. First, the catch names TransientFailure and nothing else: a PermanentFailure passes straight through, untried — no number of retries fixes an unknown address. Second, the bound is a named constant, MAX_ATTEMPTS, so the number and the reason sit in one place — and the while (true) from section 5 cannot creep back in as a literal 3 nobody questions. Third, the last failure is rethrown as itself, not wrapped and not swallowed. The retry stays silent: the logging decorator inside it records each attempt. The retry says nothing about whether the send is safe to repeat — that is the caller's job, and a non-idempotent sender must not be retried at all.

Second, the proxy. The first version denied the roles it knew about; the hardened one allows only the role it trusts. One word changes, and the default flips:

public void write(String documentId, String text) {
    if (role != Role.EDITOR) {
        throw new SecurityException("write requires the editor role");
    }
    real.write(documentId, text);
}

A role added later — an auditor, a guest, a migration script — is denied until someone deliberately grants it. Deny by default is the whole rule: the proxy's job is to say no unless the code says yes. And it never exposes the real service — no getter, private field.

Verify with explicit checks, not assertions — the same discipline as posts 1, 3, 4, and 5. Assertions can be switched off at runtime. One test double first: it always fails permanently, and counts its calls:

// The test double for the checks: it always fails permanently,
// and counts how many times it was called.
final class BadAddressNotifier implements Notifier {
    private int calls;

    public void send(String message) {
        calls++;
        throw new PermanentFailure("unknown recipient address");
    }

    int calls() {
        return calls;
    }
}

The check program throws on mismatch — and its counts prove the layers passed the call through, the one test a silent decorator cannot fake.

public class DecoratorProxyDemo {
    public static void main(String[] args) {
        // 1. Retry recovers; order: retry outside, logging inside (section 5).
        FlakyNotifier flaky = new FlakyNotifier();
        Notifier notifier = new RetryNotifier(new LoggingNotifier(flaky));
        notifier.send("Order shipped");
        check("retry recovers after two failures", flaky.attempts() == 3);

        // 2. Permanent failure: tried once.
        BadAddressNotifier badAddress = new BadAddressNotifier();
        Notifier retrying = new RetryNotifier(badAddress);
        try {
            retrying.send("hello");
            check("a permanent failure throws", false);
        } catch (PermanentFailure e) {
            check("a permanent failure throws", true);
        }
        check("permanent failure tried once", badAddress.calls() == 1);

        // 3. Giving up throws.
        AlwaysBusyNotifier alwaysBusy = new AlwaysBusyNotifier();
        Notifier retryingBusy = new RetryNotifier(alwaysBusy);
        try {
            retryingBusy.send("Order shipped");
            check("giving up throws", false);
        } catch (TransientFailure e) {
            check("giving up throws", true);
        }
        check("gives up after three attempts", alwaysBusy.calls() == 3);

        // 4. Proxy rules.
        DocumentService viewerDocs = new AccessProxy(new RealDocumentService(), Role.VIEWER);
        check("a viewer may read", viewerDocs.read("PRICE-LIST").equals("contents of PRICE-LIST"));
        try {
            viewerDocs.write("PRICE-LIST", "new prices");
            check("a viewer may not write", false);
        } catch (SecurityException e) {
            check("a viewer may not write", true);
        }
        DocumentService editorDocs = new AccessProxy(new RealDocumentService(), Role.EDITOR);
        editorDocs.write("PRICE-LIST", "new prices");
        check("an editor may write", true);
    }

    static void check(String name, boolean condition) {
        if (!condition) {
            throw new IllegalStateException("FAILED: " + name);
        }
        System.out.println("ok: " + name);
    }
}
sending: Order shipped
sending: Order shipped
sending: Order shipped
sent: Order shipped
sent ok: Order shipped
ok: retry recovers after two failures
ok: a permanent failure throws
ok: permanent failure tried once
ok: giving up throws
ok: gives up after three attempts
ok: a viewer may read
ok: a viewer may not write
wrote PRICE-LIST: new prices
ok: an editor may write

When not to use a decorator. A decorator is a whole extra class, and sometimes the behavior belongs in the class itself. As a rule of thumb — not a law — if every caller needs the behavior, always, put it in the class. And if only one caller needs the behavior once, a plain method call beats a wrapper with a name. The decorator earns its keep when the behavior varies per caller and the class must stay untouched.

When not to use a proxy. The same rule of thumb applies from the other side: if there is nothing to guard — no access rule, no expensive object to create lazily, no remote call to hide — the proxy is a pass-through with a name. And a proxy must guard, not decide: the moment it starts making business decisions, it is a service with a friendly name. Keep the decisions in the caller.

7. Communicate: explain it to a human

The code is only half the job. Here is how you explain this change to Maya, without jargon:

"Before, every place that sent an email had its own logging and its own retry, and every place that changed a document had its own check for who was allowed. Now the email sender is wrapped in layers: one writes down every send, one tries again when the mail server is busy, the sender itself untouched in the middle. And the price list has one gatekeeper: anyone can read it, only an editor can change it, the real document never handed to anyone directly. The one trade-off: the order of the layers matters, and it is written down in exactly one place, where the sender is built. Stack them differently and the log goes quiet — so that one place is the thing to review."

If she understands that paragraph, she understands the design — and she can approve the next change with confidence.

Field check

Six rules to carry into the rest of the track:

  1. A decorator adds behavior; it never changes the interface. If the caller's code has to change to use it, it is a rewrite wearing a wrapper's name.
  2. The order of the layers is part of the design. Write it down where the object is built — whoever stacks logging outside the retry gets a log that cannot see a failed attempt.
  3. Retry only what can succeed on a second try, and only a bounded number of times. A retry that never gives up is a hang, a retry of a send that already went out is a duplicate, a retry of an unfixable failure is three wasted calls.
  4. A decorator that does not delegate is a black hole. It compiles, it runs, and the work silently never happens. Count the calls in a check before trusting any wrapper.
  5. A proxy denies by default. Allow only the role you trust, refuse everything else, never hand out the real object.
  6. No decorator without a behavior to add, no proxy without something to guard. One caller, one behavior is a method call; nothing to guard is a direct reference. A pattern is a tool, not a goal.

Previous in this track: Java Adapter and Facade Patterns: Integrate Incompatible Code Cleanly · Continue: Java Observer Pattern: Events, Listeners and Reactive Design Explained

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

30 Core Java Basic Interview Questions for Freshers