Strategy
Put each interchangeable algorithm behind one interface and pass it in, so behaviour can change without if-else chains.
The problem it solves
A checkout applies a discount. At first there is one rule. Then marketing adds more, and the code becomes this:
if (type.equals("PERCENT")) { ... }
else if (type.equals("FLAT")) { ... }
else if (type.equals("CAPPED")) { ... }Problems with that:
- Every new rule means editing the same method, and an edit can break the old rules.
- The chain is hard to test, because you must set up the
typeto reach each branch. - The same chain gets copied into other places (reports, refunds).
Strategy moves each rule into its own class that implements one small interface. The checkout holds a strategy and calls it. Which one it holds can change while the program runs.
1 of 8