Design patterns through refactoring series: 1. Strategy · 2. Template Method and composition · 3. Observer and Spring events · 4. Adapter and Factory
When you integrate with the outside world, Adapter keeps a third-party SDK’s details out of your business code, and Factory creates or picks the right implementation. This post reviews two pieces of the course’s sample code (an adapter converting USD to VND with four bugs in one line, and a “factory” that is misnamed and never actually injected) and rewrites them properly (JDK 21, Lombok 1.18.42). The Spring parts build on IoC and Dependency Injection; the booking flow in section 2 is explained in part 2: Template Method.
At a glance:
flowchart LR
A[Our code] --> AD[Adapter]
AD -->|"translate types, units, errors"| PG[Payment gateway]
AD -.-> M["Money: BigDecimal/long"]
AD -.-> T["Timeout = unknown"]
F{Which factory?} -->|pick by key| S[Simple factory]
F -->|subclass decides| FM[Factory Method]
F -->|matching object family| AF[Abstract Factory]
F -->|Spring| R[Registry picks bean]
1. Adapter: integrating a payment gateway that takes VND
Key idea: an Adapter converts a class’s interface into the one the client needs, so neither side has to change. A good adapter also converts units, currency types and error codes, so none of the SDK’s details leak out.
1.1. The repo’s v1 and v2
OrderService prices things in USD, while the payment SDK (which we can’t change) expects VND. v1 calls the SDK directly with the USD amount: a customer buying for 12 USD gets charged 12 dong (“failed integration”).
v2 adds a PaymentGateway interface (taking USD) for OrderService to use, and a PaymentAdapter implementing it: convert USD to VND, then call the SDK. OrderService doesn’t know the SDK exists. The repo’s conversion:
private int convertToVND(double amount) {
return (int) amount * 26000; // USD = 26000 VND
}
1.2. Reviewing the adapter: four bugs in one line
Running that exact formula:
static int buggyConvert(double usd) { return (int) usd * 26000; }
System.out.println("buggy 12.99 USD -> " + buggyConvert(12.99) + " VND");
System.out.println("buggy 0.99 USD -> " + buggyConvert(0.99) + " VND");
System.out.println("buggy 99999 USD -> " + buggyConvert(99_999) + " VND (int overflow)");
System.out.println("double 19.99*26000 = " + (19.99 * 26000) + ", cast to long = " + (long) (19.99 * 26000));
buggy 12.99 USD -> 312000 VND
buggy 0.99 USD -> 0 VND
buggy 99999 USD -> -1694993296 VND (int overflow)
double 19.99*26000 = 519739.99999999994, cast to long = 519739
Beyond the arithmetic there are three design flaws:
- The exchange rate (26,000) is hard-coded.
- The adapter
news the SDK andOrderServiceV2news the adapter, so neither can be replaced in tests. - The adapter returns the SDK’s raw result string, so third-party details still leak into our code.
1.3. Adapter done right
A good adapter translates the third party’s whole vocabulary: money is Money (amount + currency code), results are Paid/Declined instead of "00"/"51", and the rate comes from an injected FxRates.
// adaptee: the third-party SDK
static final class LocalPayClient {
/** Amount in VND (whole dong). Returns "00" on success, other codes on failure. */
String charge(long amountVnd, String orderRef) {
if (amountVnd > 50_000_000) return "51"; // insufficient funds
return "00";
}
}
// port: what the application wants to talk to
record Money(BigDecimal amount, Currency currency) {
Money {
if (amount.scale() > currency.getDefaultFractionDigits())
throw new IllegalArgumentException("too many decimals for " + currency + ": " + amount);
}
static Money of(String amount, String code) { return new Money(new BigDecimal(amount), Currency.getInstance(code)); }
}
sealed interface PaymentResult permits Paid, Declined {}
record Paid(String orderRef, Money charged) implements PaymentResult {}
record Declined(String orderRef, String reason) implements PaymentResult {}
interface PaymentGateway { PaymentResult pay(String orderRef, Money amount); }
interface FxRates { BigDecimal rate(Currency from, Currency to); }
// adapter
static final class LocalPayAdapter implements PaymentGateway {
private static final Currency VND = Currency.getInstance("VND");
private static final Map<String, String> REASONS = Map.of("51", "INSUFFICIENT_FUNDS", "24", "CANCELLED_BY_USER");
private final LocalPayClient client;
private final FxRates fx;
LocalPayAdapter(LocalPayClient client, FxRates fx) { this.client = client; this.fx = fx; }
@Override
public PaymentResult pay(String orderRef, Money amount) {
Money vnd = toVnd(amount);
String code = client.charge(vnd.amount().longValueExact(), orderRef);
return "00".equals(code)
? new Paid(orderRef, vnd)
: new Declined(orderRef, REASONS.getOrDefault(code, "UNKNOWN_" + code));
}
private Money toVnd(Money m) {
if (m.currency().equals(VND)) return m;
BigDecimal converted = m.amount()
.multiply(fx.rate(m.currency(), VND))
.setScale(VND.getDefaultFractionDigits(), RoundingMode.HALF_UP);
return new Money(converted, VND);
}
}
Output with a fake rate, and the switch over the sealed result
With a fake rate of 26,000.50 for the demo:
Paid[orderRef=ORD-1, charged=Money[amount=337746, currency=VND]]
Paid[orderRef=ORD-2, charged=Money[amount=519750, currency=VND]]
Declined[orderRef=ORD-3, reason=INSUFFICIENT_FUNDS]
Paid[orderRef=ORD-4, charged=Money[amount=150000, currency=VND]]
rejected: too many decimals for VND: 1.5
declined: INSUFFICIENT_FUNDS
The last line comes from a switch on PaymentResult. Because the interface is sealed (only the classes in permits may implement it), the switch needs no default and the compiler insists every result is handled. Add Pending to permits and forget a call site, and it’s a compile error.
1.4. How Adapter differs from Facade, Decorator and an anti-corruption layer
| Pattern | Its interface compared with what it wraps | Purpose |
|---|---|---|
| Adapter | different: exactly what the client needs | make two mismatched interfaces work together |
| Facade | simpler: a few methods over many calls | hide a subsystem’s complexity |
| Decorator | identical | add behaviour (logging, retry, cache) without changing the interface |
| Proxy | identical | control access (lazy loading, security, remoting, Spring’s transactions) |
| Anti-corruption layer | a set of adapters + translators at the boundary | keep your bounded context’s model from being “infected” by an external one |
Object adapter or class adapter
An object adapter holds the adaptee as a field (as above). A class adapter extends the adaptee and implements the target. Java allows one superclass, and extending an SDK couples you to everything you don’t use, so you almost always want an object adapter.
Wrapping a third-party SDK behind your own interface is one case of the boundary rule in clean code; Clean code: error handling, boundaries and refactoring adds how to test that boundary without over-mocking and how to translate the SDK’s exceptions right there.
2. Factory: three different things called “factory”
Key idea: “factory” names three things: a simple factory picks an implementation via switch or lookup, Factory Method lets a subclass pick the class, and Abstract Factory creates a family of objects that must match. In Spring the container has already created the beans, so your code usually only needs to pick.
Part 2 showed a naming mix-up: the v2 booking flow’s BookingFactory carries the comment “Abstract Factory”, but it just picks one of three existing services by listing type.
| Simple factory | Factory Method | Abstract Factory | |
|---|---|---|---|
| Shape | a function/class with a switch or lookup |
one abstract method, implemented by subclasses | an interface with several creation methods |
| Produces | one object of several kinds | one object, kind chosen by the subclass | a family of objects that must match |
| Mechanism | condition or lookup | inheritance | composition (pass the factory in) |
| Example | pick the booking service by listing type | email/SMS ReceiptSender |
payment gateway: URL builder + verifier |
2.1. Simple factory: a function that picks an implementation
Not a GoF pattern, but the one you meet most. Good enough with few types in one module.
static BookingHandler simpleFactory(ListingType type, BookingHandler apartment, BookingHandler villa, BookingHandler base) {
return switch (type) { // no default: adding a constant breaks the build here
case APARTMENT -> apartment;
case VILLA -> villa;
case HOMESTAY -> base;
};
}
2.2. Registry: a simple factory that Spring wires for you
When each implementation is a bean: each bean says which type it serves (type()), you inject the whole list and build a lookup table. A missing or duplicate handler fails at startup (fail fast).
static final class BookingHandlerRegistry {
private final Map<ListingType, BookingHandler> byType = new EnumMap<>(ListingType.class);
BookingHandlerRegistry(List<BookingHandler> handlers) { // Spring injects every BookingHandler bean
for (BookingHandler h : handlers) {
BookingHandler previous = byType.putIfAbsent(h.type(), h);
if (previous != null) throw new IllegalStateException("two handlers for " + h.type());
}
EnumSet<ListingType> missing = EnumSet.complementOf(EnumSet.copyOf(byType.keySet()));
if (!missing.isEmpty()) throw new IllegalStateException("no handler for " + missing);
}
BookingHandler forType(ListingType t) { return byType.get(t); }
}
APARTMENT booking for homestay 8
startup: no handler for [HOMESTAY]
startup: two handlers for VILLA
2.3. Factory Method: the subclass decides what to create
An abstract method returns an object; the subclass picks the concrete class, and the parent uses the object without knowing what it is. It’s really a Template Method whose step is “create an object”, which is why the two often come together.
interface Receipt { String render(String bookingId); }
static abstract class ReceiptSender {
protected abstract Receipt createReceipt(); // the factory method
final String send(String bookingId) { return "sent: " + createReceipt().render(bookingId); }
}
static final class EmailReceiptSender extends ReceiptSender {
protected Receipt createReceipt() { return id -> "<html>booking " + id + "</html>"; }
}
static final class SmsReceiptSender extends ReceiptSender {
protected Receipt createReceipt() { return id -> "Booking " + id + " confirmed"; }
}
sent: <html>booking B-42</html>
sent: Booking B-42 confirmed
2.4. Abstract Factory: a family of objects that must match
Abstract Factory creates several related kinds of object that always belong to one family. Example: each payment gateway needs a payment-URL builder (signed with a secret) and a callback verifier (checking the signature with the same algorithm and secret). Mixing gateway A’s URL builder with gateway B’s verifier is a bug; a PaymentProvider that returns both makes the mix impossible.
PaymentProvider code with HMAC and constant-time comparison
interface PaymentUrlBuilder { String build(String orderRef, long amount); }
interface CallbackVerifier { boolean verify(String query, String signature); }
interface PaymentProvider { // the abstract factory
PaymentUrlBuilder urlBuilder();
CallbackVerifier callbackVerifier();
}
record HmacProvider(String name, String algorithm, String secret) implements PaymentProvider {
public PaymentUrlBuilder urlBuilder() {
return (ref, amount) -> {
String query = "amount=" + amount + "&ref=" + ref;
return "https://pay." + name + ".example/?" + query + "&sig=" + hmacHex(algorithm, secret, query);
};
}
public CallbackVerifier callbackVerifier() {
return (query, sig) -> MessageDigest.isEqual( // constant-time compare
hmacHex(algorithm, secret, query).getBytes(StandardCharsets.US_ASCII),
sig.getBytes(StandardCharsets.US_ASCII));
}
}
url length 186, verify own callback = true
verify with another provider's verifier = false
verify tampered amount = false
MessageDigest.isEqual compares every byte no matter where they differ. String.equals stops at the first differing byte, so an attacker could measure response times to guess the signature byte by byte (a timing attack).
2.5. Spring is already a factory, and the @RequiredArgsConstructor trap
The IoC container is one big factory: it creates beans, decides how many (scope) and wires dependencies. Your code needs to pick a bean (a registry), or create objects from runtime data (ObjectProvider<T> or a factory bean that takes arguments).
Because the container does the wiring, wiring bugs are hard to spot when reading code. The v2 booking flow has one in three classes: BookingV2Controller, BookingFactory and BaseBookingService all carry @RequiredArgsConstructor, but their dependency fields (all or most) are not final:
@Service
@RequiredArgsConstructor
public class BookingFactory { // Abstract Factory
private final VillaBookingService villaBookingService;
private HomestayService homestayService;
private BaseBookingService baseBookingService;
private ApartmentBookingService apartmentBookingService;
Lombok 1.18.42 experiment: the generated constructor and the NPE
I wrote two trimmed-down classes with the same kind of declarations (one with a final field and a plain field, one with no final field at all), compiled them with Lombok 1.18.42 and printed the constructors via reflection:
BookingFactory constructor params: [class Probe$PricingService]
BaseBookingService constructor params: []
Lombok only puts final fields (and uninitialised @NonNull fields) into the constructor. Plain fields aren’t injected, stay null, and the bug only shows up when a method runs:
NPE: Cannot invoke "FactoryDemo$PricingService.price(long)" because "this.pricingService" is null
Fix the finals and a second trap surfaces: the factory injects BaseBookingService by type, and ApartmentBookingService and VillaBookingService are its subclasses and beans too. Three beans match the type.
2.6. Three concepts that get mixed up: Dependency Inversion, IoC, DI
- Dependency Inversion (the D in SOLID): code depends on interfaces, not concrete classes. The service depends on
PaymentGateway, notLocalPayClient; the adapter in section 1 exists to keep that dependency direction. - Inversion of Control: the framework calls your code instead of you calling a library (“don’t call us, we’ll call you”). Template Method in part 2 is IoC at the level of one class; Spring is IoC at the level of the whole application.
- Dependency Injection: one concrete way to apply IoC to creating and wiring dependencies: the container assembles objects (beans) and hands them to you.
The course’s two pictures: pizza and a bike
- Dependency Inversion: a boss wants pizza. Without inversion, the boss depends directly on each concrete pizza (meat, vegan, cheese). With inversion, the boss depends only on “the pizza staff” (an interface), and the concrete pizzas implement it.
- Dependency Injection: building a bike yourself means buying each part from a different shop and assembling it, which is painful. With DI you tell a factory (the IoC container) which bike you want, it assembles it (a bean) and delivers it to you.
Apply Dependency Inversion to a whole codebase and you get hexagonal or clean architecture: the PaymentGateway interface lives in the business core, and the VNPay adapter sits at the edge, depending inward; see Codebase architecture: layered, hexagonal, clean.
Details on the container, scopes and injection styles are in IoC and Dependency Injection.
Exercises
Exercise 1: An adapter for an SDK that throws, where a timeout isn’t a failure
Task: an e-wallet SDK has debit(account, amount, idempotencyKey) that returns a transaction id, throws WalletDeclinedException when declined and IOException (including SocketTimeoutException) on network trouble. Write an adapter to a port of your own with explicit results, and handle the timeout case correctly.
Solution to Exercise 1: an Unknown result for timeouts
sealed interface ChargeResult permits Charged, Rejected, Unknown {}
record Charged(String providerTxId) implements ChargeResult {}
record Rejected(String reason) implements ChargeResult {}
/** Neither success nor failure: reconcile later with the same key, never retry with a new one. */
record Unknown(String idempotencyKey, String cause) implements ChargeResult {}
static final class WalletAdapter implements ChargePort {
private final WalletSdk sdk;
WalletAdapter(WalletSdk sdk) { this.sdk = sdk; }
@Override
public ChargeResult charge(String account, long amountVnd, String key) {
try {
return new Charged(sdk.debit(account, amountVnd, key));
} catch (WalletDeclinedException e) {
return new Rejected(e.getMessage());
} catch (SocketTimeoutException e) {
return new Unknown(key, "timeout");
} catch (IOException e) {
return new Unknown(key, e.getClass().getSimpleName());
}
// IllegalArgumentException is a bug in our code: let it propagate
}
}
ACC-1: mark order PAID (TX-1)
LOCKED-2: mark order PAYMENT_FAILED (ACCOUNT_LOCKED)
ACC-3: mark order PAYMENT_PENDING, schedule status query for order-ACC-3
ACC-4: bug, propagated: amount must be positive
When reading the response times out, the wallet may already have debited the money. Treat it as a failure and let the customer retry with a new key, and you charge twice; treat it as success and you ship unpaid goods. The right state is “unknown”: keep the order in PAYMENT_PENDING, query the status with the same idempotency key (a dedup key: resending it never charges twice), or wait for the callback. Programming errors (IllegalArgumentException) aren’t translated into business results, because hiding them hides bugs.
Exercise 2: Add a gateway to the Abstract Factory
Task: add a third gateway that signs with HMAC-SHA256 and uses a different signature parameter name. What do you change?
Solution to Exercise 2
Add a new PaymentProvider implementation (in the demo it’s just new HmacProvider("otherpay", "HmacSHA256", secret); a gateway with a different format gets its own class implementing both methods). The payment code doesn’t change because it only receives a PaymentProvider. Combine it with the registry from section 2.2 (keyed by gateway code) to pick a provider per order. The secret comes from a secret manager, not from code or an application.yml in git.
Remember
- Can you explain why
(int) amount * 26000loses money, and the other three bugs in that line? - Do you know what a good adapter must translate (types, units, error codes, exceptions) and why a timeout is “unknown”?
- Can you tell simple factory, Factory Method and Abstract Factory apart, with one example each?
- Do you know when to pick a switch and when a bean registry to choose an implementation?
- Can you explain the two wiring traps:
@RequiredArgsConstructorwith non-finalfields, and injecting by a parent class?
Interview questions
Junior
What is the Adapter pattern? Give an example.
An adapter wraps a class with a mismatched interface (often a third-party SDK) so it looks like the interface your code needs.
Example: your service uses a PaymentGateway taking Money, while the SDK takes an integer amount in VND and returns string codes; the adapter converts the units, calls the SDK and translates the codes into your own result type.
How does Factory Method differ from Abstract Factory?
Factory Method creates one object and lets a subclass choose its type; Abstract Factory creates a family of related objects that must match.
Factory Method is one method (often abstract). Abstract Factory is an interface with several creation methods, each implementation producing one family. A simple factory is just a switch function picking an implementation; it isn’t a GoF pattern.
Mid
Why not use double for money? What instead?
Because double is binary floating point and 19.99 isn’t exact; use BigDecimal built from strings, or a long in minor units.
Multiply and truncate and you get 519,739 instead of 519,740. Round explicitly with an agreed RoundingMode and the currency’s number of decimals.
What happens with @RequiredArgsConstructor and a non-final field?
That field isn’t in the constructor Lombok generates, so Spring doesn’t inject it and it stays null.
The app starts fine; the NPE appears only when code using the field runs. Prevent it with private final for all dependencies, static rules (IDE inspections, ArchUnit), and a context-starting test that exercises the main flows.
A factory picks an implementation with a switch that has a default branch. What’s your review comment?
Drop the default, because it makes any new enum value silently take the default path.
Without default, the switch expression must cover every constant: a new type without a factory case becomes a compile error. Or move to a registry built from List<Handler> that checks for gaps and duplicates at startup. Keep default only if “every other type takes the common path” is a documented business decision.
Senior
A call to the payment gateway times out. What should the adapter return?
An explicit “unknown” state, not a failure, because the money may already have moved.
Treating it as failed and letting the user retry with a new key charges them twice. The order stays pending; the system queries the transaction status with the same idempotency key, accepts the callback (IPN), and a reconciliation job handles orders pending for too long.
How do Adapter, Facade, Decorator and an anti-corruption layer differ?
Adapter changes an interface, Facade simplifies one, Decorator keeps it and adds behaviour, and an anti-corruption layer is a whole boundary layer that keeps an outside model out.
Facade sits in front of a complex subsystem. Decorator adds retry, logging, caching. An anti-corruption layer lives at a bounded context’s edge, made of adapters and translators, so outside error codes, concepts and units don’t leak into your domain.
Useful phrases for interviews
- “The adapter translates the provider’s codes, units and exceptions into our own types, so nothing leaks into the domain.”
- “A timeout from a payment call is an unknown outcome, not a failure; we reconcile with the same idempotency key.”
- “We store the original amount, the converted amount and the rate on the transaction.”
- “That class is a simple factory, not an abstract factory; it just picks one of the existing beans.”
- “An abstract factory guarantees the URL builder and the verifier come from the same provider.”
- “With Lombok’s RequiredArgsConstructor, a dependency that isn’t final simply never gets injected.”
- “I’d rather inject a registry by interface than rely on parameter names to resolve ambiguous beans.”
Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.