Strategy
- Java course
- Advanced
- Lesson 39/82
- 5 min
Learn the Strategy pattern.
The Strategy pattern
The Strategy makes interchangeable algorithms that do the same job. An interface defines a behavior; each concrete class is one algorithm. A context class holds a Strategy reference and can swap it at runtime.
Example: a Payment interface declares pay(int amount); CashPayment and CardPayment are two algorithms. A Cart class changes the payment method with setPayment. This gives a clean separation instead of long if-else chains.
Strategy with lambdas
If a Strategy interface has a single abstract method (a functional interface), it can be written with a lambda. Payment p = amount -> System.out.println(amount) creates a strategy without defining a new class.
This is practical for small, one-off algorithms. Complex algorithms still stay as named classes, for readability and testability. Lambdas make Strategy even more powerful.
Practice Apply the payment strategy
Define a Payment interface with void pay(int amount). A CardPayment class implements it and prints card and the amount inside pay with System.out.println ("card " + amount). A Cart class has setPayment(Payment) and checkout(int amount) methods; checkout calls p.pay(amount). In main, set CardPayment and call checkout(100).
Starter code
// Define the Payment interface and CardPayment class
// Add setPayment to the Cart class
// Call checkout in mainSample solution
interface Payment { void pay(int amount); }
class CardPayment implements Payment {
public void pay(int amount) { System.out.println("card " + amount); }
}
class Cart {
private Payment p;
public void setPayment(Payment p) { this.p = p; }
public void checkout(int amount) { p.pay(amount); }
}
public class StrategyDemo {
public static void main(String[] args) {
Cart c = new Cart();
c.setPayment(new CardPayment());
c.checkout(100);
}
}Expected output
card 100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Strategy call
cart.setPayment(new ____());
cart.setPayment(new CardPayment());
Explanation: CardPayment is a Strategy implementation.
2 When is the Strategy pattern used?
- When object wrapping is needed
- When a single instance is needed
- When the same job is done with different algorithms Correct answer
- When notifications are sent
Explanation: Strategy is used when the same job is done with different algorithms.
3 Match the Strategy parts
| Term | Meaning |
|---|---|
Payment |
Common interface |
CardPayment |
An algorithm |
setPayment |
Swap strategy |
p.pay(amount) |
Run the algorithm |