Behavioral design patterns
On this page 5 headings
Behavioural patterns handle effective communication and the assignment of responsibilities between objects.
5.1 Iterator: traverse a collection without exposing storage
Collections include lists, queues, stacks and trees of products, orders or deliveries. The client only wants to access elements, not know how they are stored. Separate element access into an iterator object. Java’s Iterator interface has hasNext(), returning true if there are more elements, and next(), returning the next element.
Example: Book (ISBN, title, cost) in an ArrayList and in a LinkedList. Each collection implements hasNext/next and the client just iterates.
Pros: SRP; OCP through new iterator types. Con: overkill for simple collections such as arrays.
5.2 Observer: notify interested subscribers automatically
Feature: notify a particular set of buyers when a new product launches, like YouTube channel subscriptions — only subscribers, not all users. Subject keeps a list of observers and notifies them automatically of changes.
Subject provides register(), unregister(), notifyObservers(); notifyObservers() iterates and calls update().
Observer is an interface/abstract class with update(). NormalUser and PrimeUser implement update(); a prime user also gets an extra-discount message.
5.3 Strategy: select an interchangeable algorithm
Feature: process orders by different strategies — first in first out, or priority (prime users first). Before: OrderManager has one method per strategy; adding a strategy means modifying the class, violating OCP. Strategy extracts each algorithm into its own class; the context delegates to a strategy object.
Interface OrderDeliveryStrategy defines deliverOrders(). FirstInFirstOutOrderDelivery and PriorityOrderDelivery implement it; a new strategy is just a new class.
Pros: isolates algorithm implementation; OCP. Con: not required if only one or two algorithms will be used.
5.4 Observer versus Strategy versus Iterator
Observer broadcasts changes to subscribers. Strategy swaps the algorithm used to perform a task. Iterator moves through elements of a collection. All three are behavioral, but the reasons for using them are different.
Summary
Patterns are templates/descriptions for organising objects and classes to solve general design problems in a context. There are about 23 patterns; the course covers a few. Weigh their benefits and drawbacks: patterns should not be used blindly, only when they give a benefit.
