Singleton, Factory Method and Strategy: Code and Compare in Java
Data Structure DesignModel answerLast updated
Write Java versions of a lazy thread-safe Singleton, a Factory Method and a Strategy, weigh them against each other, then refactor a Singleton dependency to use injection.
You are asked to demonstrate practical command of three classic object-oriented design patterns in Java.
Part 1: Implement
- A Singleton that is both lazily created and safe under concurrent access. Be ready to explain why your approach is correct from a memory-model point of view.
- A Factory Method example in which a base class owns a workflow and subclasses decide which concrete collaborator gets created.
- A Strategy example in which several interchangeable algorithms sit behind one interface and can be swapped at runtime.
Part 2: Compare
Contrast the three patterns on these axes:
- the problem each one solves
- extensibility
- testability
- typical risks and costs
Part 3: Refactor
Choose one of your examples, ideally one that reaches a Singleton through a static call, and refactor it to reduce coupling and allow dependency injection. Show the code before and after, and explain what you gain when writing unit tests.
You are not expected to use a DI framework. Plain constructor injection is enough. State any assumptions you make.
Hints
Hint 1
For a lazy, thread-safe Singleton, think about what the JVM already guarantees about class initialization, and about when a nested class is first loaded. If you choose double-checked locking, ask what the field must be declared as, and why.
Hint 2
Factory Method relies on inheritance: the base class calls an overridable creation method and works only against an interface. A plain `switch`-based helper is a different thing (a simple or static factory), so know the difference.
Hint 3
For the refactor, extract an interface for the Singleton's behavior, pass it through the constructor, and keep the real implementation wired up in one place (the composition root). Then show how a test passes in a fake.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The three patterns answer different questions:
- Singleton (creational): how do I ensure exactly one instance, reachable from anywhere?
- Factory Method (creational): how do I let subclasses choose which concrete class to instantiate while the base class keeps the workflow?
- Strategy (behavioral): how do I make an algorithm swappable without changing the code that uses it?
1. Singleton: lazy and thread-safe
Preferred: initialization-on-demand holder.
public final class AppSettings {
private final Map<String, String> values = new ConcurrentHashMap<>();
private AppSettings() { /* load configuration */ }
private static final class Holder {
static final AppSettings INSTANCE = new AppSettings();
}
public static AppSettings getInstance() { return Holder.INSTANCE; }
public String get(String key) { return values.get(key); }
}
Why this works:
Holderis not loaded untilgetInstance()is first called, so creation is lazy.- The JVM guarantees class initialization happens once, under an internal lock, with safe publication. No explicit synchronization is needed.
- The steady-state cost is a plain static field read.
Alternative: double-checked locking, useful when construction needs runtime arguments or the instance must be resettable.
public final class Pool {
private static volatile Pool instance;
private Pool() {}
public static Pool getInstance() {
Pool local = instance;
if (local == null) {
synchronized (Pool.class) {
local = instance;
if (local == null) instance = local = new Pool();
}
}
return local;
}
}
volatile is essential. Without it, reordering can let another thread see a non-null reference to a partially constructed object.
Alternative: single-element enum. It is robust against serialization and reflection attacks, but it cannot extend a class and is initialized when loaded.
2. Factory Method
interface Sender { void send(String to, String body); }
class SmsSender implements Sender {
public void send(String to, String body) { /* gateway call */ }
}
class SlackSender implements Sender {
public void send(String to, String body) { /* webhook call */ }
}
abstract class AlertService {
protected abstract Sender createSender(); // factory method
public final void alert(String to, String body) {
createSender().send(to, body);
}
}
class SmsAlertService extends AlertService {
protected Sender createSender() { return new SmsSender(); }
}
class SlackAlertService extends AlertService {
protected Sender createSender() { return new SlackSender(); }
}
The base class holds the algorithm skeleton and knows only Sender. Each subclass picks the product. A SenderFactory.create(type) with a switch is a simple factory, which is often perfectly fine but is not the GoF pattern.
3. Strategy
@FunctionalInterface
interface PricingRule { BigDecimal apply(BigDecimal subtotal); }
class FlatRate implements PricingRule {
public BigDecimal apply(BigDecimal s) { return s; }
}
class PercentOff implements PricingRule {
private final BigDecimal rate;
PercentOff(BigDecimal rate) { this.rate = rate; }
public BigDecimal apply(BigDecimal s) {
return s.multiply(BigDecimal.ONE.subtract(rate));
}
}
class Cart {
private PricingRule rule;
Cart(PricingRule rule) { this.rule = Objects.requireNonNull(rule); }
void useRule(PricingRule r) { this.rule = Objects.requireNonNull(r); }
BigDecimal total(BigDecimal subtotal) { return rule.apply(subtotal); }
}
// A lambda works as a strategy too:
cart.useRule(s -> s.subtract(new BigDecimal("5")).max(BigDecimal.ZERO));
This is composition over inheritance. New rules are added without modifying Cart (Open/Closed Principle), and the rule can change at runtime.
4. Comparison
| Aspect | Singleton | Factory Method | Strategy |
|---|---|---|---|
| Intent | One shared instance | Defer which class is created | Swap how work is done |
| Mechanism | Private constructor, static accessor | Inheritance, overridden creator | Composition, interface field |
| Extensibility | Poor; hard to vary or subclass | Good; one subclass per product | Excellent; new class or lambda, runtime swap |
| Testability | Poor; global state persists across tests | Moderate; a test subclass can return a fake | Excellent; inject a stub |
| Main cost | Hidden coupling, shared mutable state | Parallel class hierarchies | Caller must choose the right strategy |
Notes on trade-offs:
- Singleton is a global variable in disguise. Callers bind to a concrete class through a static call, so mocking needs tooling such as
mockStatic. - Factory Method removes coupling to concrete products, but the choice is fixed at compile time per subclass and the number of classes grows.
- Strategy is the most flexible. The patterns combine well: a factory often returns a strategy, and a Singleton often hosts a stateless strategy.
5. Refactor a Singleton for dependency injection
Before:
class OrderService {
Receipt place(Order o) {
return PaymentGateway.getInstance().charge(o.total()); // hard-wired
}
}
Problems: OrderService depends on a concrete class, tests would hit the real gateway, and state leaks between tests.
After:
interface PaymentGateway { Receipt charge(BigDecimal amount); }
final class StripeGateway implements PaymentGateway {
public Receipt charge(BigDecimal amount) { /* real call */ return new Receipt(); }
}
class OrderService {
private final PaymentGateway gateway;
OrderService(PaymentGateway gateway) {
this.gateway = Objects.requireNonNull(gateway);
}
Receipt place(Order o) { return gateway.charge(o.total()); }
}
// Composition root (main or DI container config):
PaymentGateway gw = new StripeGateway();
OrderService svc = new OrderService(gw);
The "single instance" requirement moves to the composition root, which creates one gateway and shares it. A DI container can do the same with singleton scope. The class itself no longer enforces uniqueness.
Test:
@Test
void chargesOrderTotal() {
PaymentGateway fake = amt -> new Receipt(amt);
OrderService svc = new OrderService(fake);
assertEquals(new BigDecimal("42"), svc.place(orderOf("42")).amount());
}
No network, no static state, and tests run in parallel safely.
Common mistakes
- Double-checked locking without
volatile. - Using
synchronizedon everygetInstance()call and paying lock cost forever. - Calling a
switch-based helper "Factory Method". - Making Singleton state mutable and unsynchronized.
- Letting a Strategy hold hidden shared state, which makes it unsafe to reuse across threads.
- Refactoring to an interface but still calling
getInstance()inside the constructor, which keeps the coupling.
Follow-ups to be ready for
- How does serialization or reflection break a classic Singleton, and how does an enum prevent it?
- When is a Singleton still acceptable (stateless, immutable, or truly process-wide resources such as a logger)?
- How would you combine a factory with Strategy so the strategy is chosen from configuration?