Which design patterns come up most often in Java interviews, and how do you implement the strategy pattern?
The patterns that come up most are strategy, observer, factory, singleton, builder and template method. They come up because each of them solves a shape of problem that recurs: swapping behaviour at runtime, notifying many parties, creating objects of varying types, ensuring a single instance, building complex objects, and fixing the skeleton of an algorithm while varying its steps.
The strategy pattern replaces a conditional with a family of interchangeable implementations behind a common interface. The client holds a reference to the interface and delegates to it, so adding a new behaviour means adding a new class rather than editing the client.
public class Main {
public static void main(String[] args) {
PaymentService service = new PaymentService(new CardPayment());
service.pay(100);
service.setStrategy(new PayPalPayment());
service.pay(200);
service.setStrategy(new CryptoPayment());
service.pay(300);
}
}
interface PaymentStrategy {
void pay(int amount);
}
class PaymentService {
private PaymentStrategy strategy;
PaymentService(PaymentStrategy strategy) {
this.strategy = strategy;
}
void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
void pay(int amount) {
strategy.pay(amount);
}
}
class CardPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("paid " + amount + " by card");
}
}
class PayPalPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("paid " + amount + " by paypal");
}
}
class CryptoPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("paid " + amount + " in crypto");
}
}The output shows the same client handling three different behaviours. The payment service never mentions cards, PayPal or crypto — it only knows the interface.
What makes it a good answer is naming the cost as well as the benefit. A strategy is more classes and more indirection, and the client still has to be told which strategy to use. If you find yourself with three strategies and no sign of more, the pattern is premature.