L12: Starting to exchange behaviour at runtime Flashcards
Strategy: Aim, what does it do, what is it used for?
The strategy aims to make behaviour interchangeable.
Encapsulate different algorithms and allow to exchange these at runtime
- Enable to call an algorithm independent of client (thus, interfacing not inheritance)
- Allow to decide at runtime what algorithm shall be used
- Provide extension point (new strategies)
Used for deciding upon most appropriate strategies at runtime like
- Payment methods (credit cards, bank transfer, app, …)
- Data compression/encryption (gzip, zip. LZW, RSA, PGP, …)
- Converting file formats (pdf/txt, jpg/png, …)
- Output format/formatting (XML, JSON, YAML, …)
Problems with strategy
Very flexible:
- Anyone can implement new strategies
- Selection of strategy not safeguarded
- Initialising strategies again loses information
Is this always useful/wanted? (fixed payment methods or accounts)
Being careful with the strategy
- Strategies must be defined, understandable, and selectable by clients
- Interface must define all methods (even if not relevant for some strategies)
- Additional classes/objects (context stores strategy/ies)
- Code becomes more complicated (not very useful for only few strategies)
Iterator: What it does, what it is, what it is used for?
The iterator allows to access elements of an object
Define access to elements in aggregate object:
- Without exposing underlying design (list, matrix, tree, graph, …)
- Iterate through elements in defined order (go over list, tree, …)
- Separates storing of data in object from accessing/traversing that data
(particularly helpful if the data gets updated while traversing by adding/removing elements)
Used for:
- Many data structures and collections internally use iterators (Java interface Collection must implement iterator(), for instance, ArrayList)
Being careful with the iterator
- Iterators are used for sequential access
- Can be infeasible if language provides built-in alternatives
- Fixed structures do not benefit from the iterator (only overhead)
- Controlling and robustness of (deleting, updating on change) the iterator (a problem with iterating over any data structure in any way!)