2IRR00 · Topic 12
Behavioral Patterns
Strategy, Iterator, Template Method, State (+ key contrasts)
Strategy (a.k.a. policy)
Strategy encapsulates a family of interchangeable algorithms behind a common interface and lets the client pick/swap one at runtime (via composition).
Interface-based (not inheritance): the context HAS-A strategy object and delegates to it; setStrategy() swaps it at runtime.
Provides an explicit extension point: add new strategies without touching the context.
Used for payment methods, compression/encryption, file-format conversion, output formatting.
Trade-offs: the interface must declare all methods (even if irrelevant to some strategies); extra classes/objects; overkill for very few strategies. Using an enum to predefine strategies trades flexibility for safety.
interface Payment { boolean processTransaction(Transaction t); }
class CreditCardPayment implements Payment { /* ... */ }
class BankTransferPayment implements Payment { /* ... */ }
service.setPaymentStrategy(new CreditCardPayment());
service.pay(t); // delegates to the current strategyCommon mistakes
- Using strategy when there are only one or two fixed behaviours (unnecessary complexity).
Exam tips
- Strategy = composition + same goal, different interchangeable implementations, chosen by the client at runtime.
Strategy (a.k.a. policy) practice
1 questions
Iterator
Iterator provides sequential access to the elements of an aggregate object without exposing its underlying structure (list, tree, graph).
Separates storing data from traversing it — useful when the data may be updated while traversing.
Structure: an Aggregate with createIterator() and an Iterator with hasNext()/next() (and optionally hasPrevious()/previous()).
Different traversal orders (in/pre/post-order, breadth-first for trees) become different iterators; you can use Strategy to pick one.
Java collections use this: the Collection interface requires iterator().
Common mistakes
- Modifying a list directly while looping over it (use the iterator; update the iterator if the structure changes).
- Adding an iterator to a fixed/simple structure where it's pure overhead.
Exam tips
- Iterator = traverse an aggregate without exposing its internal representation; different orders = different iterators.
Iterator practice
1 questions
Template Method
Template Method defines the skeleton of an algorithm in a base class and lets subclasses refine specific steps ('hook' methods) without changing the overall structure.
Separates the invariant skeleton from variant steps; abstract methods MUST be overridden, concrete (default) methods MAY be overridden.
Uses inheritance and operates on the CLASS level (changes apply to all objects, statically).
Used for AbstractList, games, loggers, data validation. Often combined with Strategy for parts that need composition (since Java lacks multiple inheritance).
abstract class LoggerTemplate {
public void logMsg(Message m) { // the template method (skeleton)
String s = formatMsg(m);
write(s);
}
protected abstract String formatMsg(Message m); // must override
protected abstract void write(String s); // must override
}Common mistakes
- A subclass not implementing all required steps can violate Liskov substitution.
Exam tips
- Template = inheritance, class-level, fixed skeleton + overridable steps.
Template Method practice
1 questions
State (+ Strategy vs Template vs State)
State lets an object alter its behaviour when its internal state changes, by delegating to state objects — it appears to change class. Structurally identical to Strategy, but with a different intent.
Fixed set of states, only one active; triggers cause specific transitions; closely related to state machines. States explicitly link to one another (a state sets the next state).
Strategy vs Template: Strategy = composition, swaps the ENTIRE algorithm dynamically per object; Template = inheritance, modifies PARTS of an algorithm statically for all objects (class level).
Strategy vs State: Strategy = a family of interchangeable behaviours with the SAME goal, chosen by the client; State = behaviour may change COMPLETELY between states, and states are explicitly linked to each other (the object drives transitions).
Key differentiator between look-alike patterns is INTENT.
interface PlayerState { void handle(Player p, Trigger t); }
class StandingState implements PlayerState {
public void handle(Player p, Trigger t) {
if (t == Trigger.PRESS_UP) { /* jump */ p.setState(new JumpingState()); }
}
}
// Player.reactToTrigger(t) → state.handle(this, t)Common mistakes
- State machine is small ⇒ State pattern may be over-engineering.
Exam tips
- Template vs Strategy (3-point open Q): inheritance vs composition; modify parts vs swap whole; class-level/static vs object-level/dynamic.
- Strategy vs State: same goal/client-chosen vs complete behaviour change/states linked to each other.
State (+ Strategy vs Template vs State) practice
1 questions