Strategy
Strategy puts a family of algorithms behind one interface and lets the client pick which one to run. You swap behaviour without a growing if/else on type flags.
Detailed Explanation
A Fee might be GST, VAT, or none. A switch on country grows with every country. A FeePolicy interface with int apply(int paise) lets you pass Gst.INSTANCE or Vat.uk(). The calculator depends on the interface. New policies are new classes.
Comparator is a strategy for sort. java.nio.charset.Charset encoding strategies sit behind one type. Lambdas made small strategies cheap: list.sort(comparing(User::name)) is a strategy object the compiler writes.
Strategy vs state: state objects may change which strategy is active as part of their job. Strategy is chosen by the client and usually stays. Strategy vs template method: template method fixes the skeleton in a superclass and varies steps by subclass; strategy varies the whole algorithm by composition.
You reach for strategy when you have several interchangeable policies. You keep a switch when the set is closed and tiny and next to the data (sometimes a sealed type plus switch is clearer). You do not create a strategy interface for one implementation.
The cost of too many one-line strategy classes is navigation. Use enums with methods or lambdas when the policy is small. The cost of a strategy that needs half the application's internals is a bad split; pass the data it needs.
Inject the strategy in the constructor. Tests pass a fake policy. That is dependency injection of a behaviour.
Keep the strategy interface small: one method, or two if they truly travel together. A strategy that needs ten callbacks is a template method in disguise, and inheritance may be clearer. Document what the calculator guarantees when the strategy throws. Empty implementations should be real types (NoFee) so callers never pass null and hope.
Code Examples
interface Fee {
int apply(int paise);
}
class Gst implements Fee {
@Override
public int apply(int paise) {
return paise + paise * 18 / 100;
}
}
class None implements Fee {
@Override
public int apply(int paise) {
return paise;
}
}
class Cart {
private final Fee fee;
Cart(Fee fee) {
this.fee = fee;
}
int total(int paise) {
return fee.apply(paise);
}
public static void main(String[] args) {
System.out.println(new Cart(new Gst()).total(10000)); // prints: 11800
System.out.println(new Cart(new None()).total(10000)); // prints: 10000
}
}Common Gotchas
A strategy that reaches into global state is not testable
pass data in.
Null strategy
use a `None` implementation instead of `if (fee == null)`.
Closed-world enums plus a switch can be simpler than six classes
Closed-world enums plus a switch can be simpler than six classes