Behavioral Patterns Part 1: Strategy, State, and Template Method
Learn how to vary algorithms, model changing object behavior, and define reusable processing skeletons in Java applications.
Inside this chapter
- Strategy Pattern
- State Pattern
- Template Method
- Choosing Among Them
- Real-World Usage Snapshot
Series navigation
Study the chapters in order for the clearest path from first design principles to advanced Java architecture, framework usage, and interview-level pattern mastery. Use the navigation at the bottom of the page to move through the full tutorial smoothly.
Strategy Pattern
Strategy encapsulates interchangeable algorithms behind a common interface. It is ideal when business rules vary by country, customer tier, payment mode, pricing policy, or sorting logic.
interface DiscountStrategy {
double apply(double amount);
}
class PremiumDiscountStrategy implements DiscountStrategy {
public double apply(double amount) {
return amount * 0.8;
}
}
class BillingService {
private final DiscountStrategy strategy;
BillingService(DiscountStrategy strategy) {
this.strategy = strategy;
}
double finalAmount(double amount) {
return strategy.apply(amount);
}
} State Pattern
State models an object whose behavior changes based on internal state. Instead of large if or switch blocks, state-specific classes hold the behavior. Order processing, workflow engines, media playback, and user onboarding state machines are good candidates.
Template Method
Template Method defines the structure of an algorithm in a base class while allowing subclasses to customize some steps. It is useful when workflows share common sequencing but vary in one or two steps.
abstract class DataExporter {
public final void export() {
readData();
transform();
writeOutput();
}
protected abstract void readData();
protected abstract void transform();
protected abstract void writeOutput();
} Choosing Among Them
| Pattern | Primary Force |
|---|---|
| Strategy | Swap algorithms or business rules. |
| State | Change behavior as object state evolves. |
| Template Method | Reuse a stable process skeleton. |
Real-World Usage Snapshot
Pricing engines use strategy, workflow systems use state, and many framework hooks use template method. These patterns are central to writing code that remains easy to extend while keeping business logic readable.