Which design patterns come up most often in Java interviews, and how do you implement the strategy pattern?
The ones that come up most often are the strategy pattern, the observer pattern, the factory pattern, the builder pattern and the singleton. The strategy one is the easiest to explain and the most useful to know properly.
The strategy pattern says that a family of algorithms goes behind one interface, and the client holds a reference to whichever one it wants. You can change the behaviour at run time without changing the client.
public class Main {
public static void main(String[] args) {
// The client does not know which strategy it is using.
PaymentService service = new PaymentService(new CardPayment());
service.pay(100);
// The strategy can be changed at any time.
service.setStrategy(new BankTransferPayment());
service.pay(250);
}
}
interface PaymentStrategy {
void pay(int amount);
}
class CardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("paying " + amount + " by card");
}
}
class BankTransferPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("paying " + amount + " by bank transfer");
}
}
class PaymentService {
private PaymentStrategy strategy;
PaymentService(PaymentStrategy strategy) {
this.strategy = strategy;
}
void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
void pay(int amount) {
this.strategy.pay(amount);
}
}
So why is it worth knowing? Because it is the answer to a very common problem. You have a class with a long method that branches on the kind of thing it is dealing with, and every time a new kind arrives you have to edit that method. The strategy pattern moves each branch into its own class, and the long method disappears.
The next question in this topic looks at the observer pattern.