Adapter vs Decorator vs Proxy
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's payment gateway ends up wrapped three times: for a third-party SDK, for logging, and to block big payments from new accounts. The code looks alike, so naming each wrapper needs a clear test.
All three wrap an object: what changes in each
A wrapper is an object that holds another object and passes calls on to it, doing something before or after. Adapter, Decorator and Proxy are three kinds of wrapper.
In ShopLite's payment flow all three kinds can sit in one chain. The code below stacks a proxy, a decorator and an adapter around one payment SDK.
Example 1 · Adapter, Decorator and Proxy in one chain
import java.math.BigDecimal;
interface PaymentGateway { boolean charge(String orderId, BigDecimal rupees);}
class PayNowSdk { int makePayment(String reference, long paise) { System.out.println(" [SDK] makePayment " + reference + " " + paise + " paise"); return 0; }}
// Adapter: different interface outside, SDK insideclass PayNowAdapter implements PaymentGateway { private final PayNowSdk sdk;
PayNowAdapter(PayNowSdk sdk) { this.sdk = sdk; }
public boolean charge(String orderId, BigDecimal rupees) { long paise = rupees.movePointRight(2).longValueExact(); return sdk.makePayment(orderId, paise) == 0; }}
// Decorator: same interface, adds behaviourclass LoggingGateway implements PaymentGateway { private final PaymentGateway inner;
LoggingGateway(PaymentGateway inner) { this.inner = inner; }
public boolean charge(String orderId, BigDecimal rupees) { System.out.println(" [log] charging " + orderId + " Rs. " + rupees); boolean ok = inner.charge(orderId, rupees); System.out.println(" [log] result " + ok); return ok; }}
// Proxy: same interface, controls whether the real call happensclass LimitCheckProxy implements PaymentGateway { private final PaymentGateway real; private final BigDecimal limit;
LimitCheckProxy(PaymentGateway real, BigDecimal limit) { this.real = real; this.limit = limit; }
public boolean charge(String orderId, BigDecimal rupees) { if (rupees.compareTo(limit) > 0) { System.out.println(" [proxy] blocked " + orderId + ": above Rs. " + limit + " for a new account"); return false; } return real.charge(orderId, rupees); }}
public class ThreeWrappersDemo { public static void main(String[] args) { PaymentGateway gateway = new LimitCheckProxy( new LoggingGateway(new PayNowAdapter(new PayNowSdk())), new BigDecimal("5000"));
System.out.println("ORD-1 result: " + gateway.charge("ORD-1", new BigDecimal("1499.50"))); System.out.println("ORD-2 result: " + gateway.charge("ORD-2", new BigDecimal("24999.00"))); }} [log] charging ORD-1 Rs. 1499.50
[SDK] makePayment ORD-1 149950 paise
[log] result true
ORD-1 result: true
[proxy] blocked ORD-2: above Rs. 5000 for a new account
ORD-2 result: falseWhat this code does
PayNowAdapterturns rupees into paise andmakePaymentintocharge;LoggingGatewayadds log lines;LimitCheckProxydecides whether the call goes through.- ORD-2 is stopped by the proxy, so neither the log lines nor the SDK call happen.
The outside view tells them apart. The adapter's interface (PaymentGateway) is different from the SDK's (makePayment with paise). The decorator and the proxy have the same interface as the object they wrap; one adds logging, the other decides whether the call happens at all.
Adapter changes the interface; Decorator adds behaviour; Proxy controls access
An Adapter makes an object fit an interface it does not have. A Decorator has the same interface and adds behaviour. A Proxy has the same interface and controls access to the real object.
Each wrapper changes one thing: the interface, the behaviour or the access. The code below puts a decorator and a proxy around the same product catalogue.
Example 2 · Same shape, different intent
import java.util.HashMap;import java.util.Map;
interface ProductCatalog { String findName(int id);}
class DbCatalog implements ProductCatalog { public String findName(int id) { System.out.println(" (database read for " + id + ")"); return id == 7 ? "Earbuds" : "Notebook"; }}
// Decorator: adds a feature the caller asked for, can be stackedclass UpperCaseNames implements ProductCatalog { private final ProductCatalog inner; UpperCaseNames(ProductCatalog inner) { this.inner = inner; } public String findName(int id) { return inner.findName(id).toUpperCase(); }}
// Proxy: decides whether the real object is called at allclass CachingCatalog implements ProductCatalog { private final ProductCatalog real; private final Map<Integer, String> cache = new HashMap<>(); CachingCatalog(ProductCatalog real) { this.real = real; } public String findName(int id) { if (!cache.containsKey(id)) { cache.put(id, real.findName(id)); } return cache.get(id); }}
public class DecoratorVsProxyDemo { public static void main(String[] args) { ProductCatalog shown = new UpperCaseNames(new DbCatalog()); System.out.println("Decorator: " + shown.findName(7)); System.out.println("Decorator: " + shown.findName(7));
ProductCatalog cached = new CachingCatalog(new DbCatalog()); System.out.println("Proxy: " + cached.findName(7)); System.out.println("Proxy: " + cached.findName(7)); }} (database read for 7)
Decorator: EARBUDS
(database read for 7)
Decorator: EARBUDS
(database read for 7)
Proxy: Earbuds
Proxy: EarbudsWhat this code does
- The decorator always calls the database and changes the result; the second call reads the database again.
- The caching proxy calls the database only on a miss, so the second call never reaches the real object.
Adapter: translates names, units and error codes. Decorator: adds a feature such as logging, retry or buffering; the caller chooses it, and decorators are often stacked. Proxy: controls access with lazy creation, caching, permission checks or remote calls; the caller usually does not know it is there.
Decorator and Proxy have the same shape, so intent is the only test. If the wrapper may skip the real call (cache hit, access denied, not loaded yet), think Proxy. If it always calls through and adds something, think Decorator.
Find the bug
Break the wrapper rule
Click the line where the wrapper stops doing its job.
This Decorator should log and then charge. Which line breaks it?
Round 1 of 2Facade vs Adapter: simplify vs translate
A facade is a new, simpler interface over a group of objects. One method such as placeOrder hides several calls behind it, so callers deal with fewer things.
CheckoutFacade.placeOrder hides inventory, payment and notification calls behind one method. The code below also uses an adapter for SMS inside it.
Example 3 · A facade that uses an adapter
import java.math.BigDecimal;
interface NotificationService { void send(String to, String message);}
// Adapter: ONE old object made to fit an EXISTING interfaceclass OldSmsApi { void sendText(String mobile, String body, int priority) { System.out.println(" [old SMS] to " + mobile + " (p" + priority + "): " + body); }}
class SmsAdapter implements NotificationService { private final OldSmsApi api; SmsAdapter(OldSmsApi api) { this.api = api; } public void send(String to, String message) { api.sendText(to, message, 1); }}
// Subsystems behind the facadeclass Inventory { boolean reserve(String product) { System.out.println(" reserve " + product); return true; }}
class Payments { boolean charge(String orderId, BigDecimal amount) { System.out.println(" charge Rs. " + amount); return true; }}
// Facade: MANY objects behind a NEW, simpler interfaceclass CheckoutFacade { private final Inventory inventory = new Inventory(); private final Payments payments = new Payments(); private final NotificationService notifications;
CheckoutFacade(NotificationService notifications) { this.notifications = notifications; }
String placeOrder(String orderId, String product, BigDecimal amount, String phone) { if (!inventory.reserve(product)) return orderId + " out of stock"; if (!payments.charge(orderId, amount)) return orderId + " payment failed"; notifications.send(phone, "Order " + orderId + " confirmed"); return orderId + " placed"; }}
public class FacadeVsAdapterDemo { public static void main(String[] args) { CheckoutFacade checkout = new CheckoutFacade(new SmsAdapter(new OldSmsApi())); System.out.println(checkout.placeOrder("ORD-21", "Earbuds", new BigDecimal("1499.00"), "98xxxxxx10")); }} reserve Earbuds
charge Rs. 1499.00
[old SMS] to 98xxxxxx10 (p1): Order ORD-21 confirmed
ORD-21 placedWhat this code does
CheckoutFacadeoffers one new method over three subsystems; callers no longer call inventory, payment and SMS themselves.SmsAdapterwraps one old object so it fits the existingNotificationServiceinterface.
A Facade gives a new, simpler interface to a group of objects. An Adapter makes one object fit an existing interface: SmsAdapter makes an old SMS API look like NotificationService.
So a facade reduces the number of things callers deal with, and an adapter makes one thing compatible. They often appear together, as here, where the facade uses an adapter for SMS.
Comparison with ShopLite examples
One question and one ShopLite case for each pattern:
- Adapter: "Does it fit our interface?"
PayNowAdapterturnsmakePayment(ref, paise)intocharge(orderId, rupees). - Decorator: "What extra do we want around the call?"
LoggingGateway,RetryGateway, gift-wrap price add-ons; stackable, order matters. - Proxy: "Should this call reach the real object now?" Caching catalogue, admin-only price updates, lazy product images, Spring's
@Transactional. - Facade: "Can callers make one call instead of five?"
CheckoutFacade.placeOrder,ReturnFacade.returnOrder.
Identifying the pattern from a code snippet
Use three checks in order. The code below names the wrapper in four java.io and collection snippets, so you can check your answers against real library classes.
Example 4 · Naming the wrapper in four JDK snippets
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.StringReader;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class IdentifyWrapperDemo { public static void main(String[] args) throws IOException { // 1. Takes an InputStream (bytes), gives a Reader (chars): a different interface -> Adapter InputStreamReader chars = new InputStreamReader( new ByteArrayInputStream("UPI".getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); System.out.println("1 Adapter: first char " + (char) chars.read());
// 2. A Reader around a Reader, adds readLine: same family, extra feature -> Decorator BufferedReader lines = new BufferedReader(new StringReader("line one\nline two")); System.out.println("2 Decorator: " + lines.readLine());
// 3. A List around a List that refuses writes: same interface, controls access -> Proxy List<String> real = new ArrayList<>(List.of("Earbuds")); List<String> guarded = Collections.unmodifiableList(real); try { guarded.add("Hoodie"); } catch (UnsupportedOperationException e) { System.out.println("3 Proxy: write refused, size still " + guarded.size()); }
BufferedReader twice = new BufferedReader(new BufferedReader(new StringReader("stacked"))); System.out.println("4 Decorator: " + twice.readLine()); }}1 Adapter: first char U 2 Decorator: line one 3 Proxy: write refused, size still 1 4 Decorator: stacked
What this code does
- 1 has a different interface outside (Reader) than inside (InputStream): Adapter. 2 and 4 keep the Reader interface and add
readLine: Decorator, and it can be stacked. - 3 keeps the
Listinterface but refuses writes: it controls access to the real list, like a protection proxy.
First, compare the wrapper's interface with the wrapped object's: different means Adapter. Second, if they are the same, ask whether the wrapper can stop or replace the real call: yes means Proxy. Third, if it always calls through and adds something, it is a Decorator.
InputStreamReader (bytes in, characters out) is an Adapter, BufferedReader around a Reader is a Decorator, and Collections.unmodifiableList behaves like a protection proxy.
Predict the output
Name the wrapper
Use the three checks and pick the pattern.
Round 1 of 3
Which pattern is TimedGateway?
Next step
Check your understanding
12 quick questions