L13: Continuing to exchange behaviour at runtime Flashcards
Template: what it does, what it is, what it is used for
The template defines behavior with refinable steps.
Implement an extensible skeleton of an algorithm
- Subclasses can refine individual steps (without impacting the general structure)
- Separate constant (invariant) skeleton from variable (variant) steps
- Define concrete extension points (“hook” methods)
Used for:
- Providing templates in programming languages (e.g., Java AbstractList)
- Games
- Loggers
- Data validation
Problems with template?
Need some flexibility/checks
- Formatting of messages
- Distinguish between message and time logging
- Prevent incorrect inputs/customizations
Notes regarding templates
- Non-abstract methods can be ignored by extension (uses default) -> Optional refinements (theoretically, even the template method can be exchanged)
- Abstract methods must be implemented by extension -> Mandatory/expected refinements
Being careful with the template
- Can challenge comprehension and maintenance (complexity, indirections, inheritance, … of many steps and extensions)
- Without multiple inheritance, some tweaks and workarounds needed (previous example if we could use multiple inheritance for formatting, time, …)
- May violate Liskov Substitution (oiof a subclass does not define all interface methods)
Template vs Strategy
Template method:
- Builds on inheritance
- Modifies parts of an algorithm via subclasses
- Done on class level, so changes are done statically and to all objects
Strategy:
- Builds on composition
- Exchanges the entire algorithm by supplying strategy object
- Done on object level, so changes are done dynamically and impact one object
State: what it does, what it is, what it is used for?
The state alters object behavior on internal change.
Separate state-dependent behavior into own, referenced units
- Fixed number of states, of which only once can be active
- A set of triggers causes specific state changes (i.e., a trigger causes a specific change from one specific to another specific state)
- Closely related to state machines
Used for
- Game development (e.g., character control)
- State machines
Strategy vs state
State:
- Behaviour may change completely between states (different goals, depending on state)
- Each state explicitly linked to other states
Strategy:
- Family of exchangeable behaviors (same goal, different implementation)
- Client can flexibly use/change strategies (if known)
Structure of state and strategy are identical
Being careful with the state
- Can be overkill if the represented state machine is small
- May be over-engineering the problem
- Hardcoded state changes (reducing flexibility and extensibility)