Behavioural Patterns
Behavioral patterns take care of effective communication and the assignment of responsibilities between objects.
Overview of Behavioral Patterns
Section titled “Overview of Behavioral Patterns”| Pattern | Purpose |
|---|---|
| Strategy | Define a family of algorithms, put each in a separate class, and make their objects interchangeable |
| Observer | Define a subscription mechanism to notify multiple objects about events happening to observed objects |
| Command | Turn requests into stand-alone objects containing all request information |
| Iterator | Traverse elements of a collection without exposing the underlying representation |
| State | Let an object alter its behavior when its internal state changes |
| Chain of Responsibility | Pass requests along a chain of handlers where each decides to process or forward |
| Template Method | Define the skeleton of an algorithm in a superclass, letting subclasses override specific steps |
| Visitor | Separate algorithms from the objects on which they operate |
| Mediator | Reduce chaotic dependencies by forcing objects to collaborate through a mediator |
| Memento | Store and restore the previous state of an object without revealing implementation details |
Strategy Pattern
Section titled “Strategy Pattern”Key Components
Section titled “Key Components”- Context: Maintains a reference to a Strategy object and delegates it to execute the algorithm
- Strategy: Common interface for all concrete strategies
- ConcreteStrategy: Implements the algorithm using the Strategy interface
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- Navigation Apps - Calculate routes using different strategies (fastest, shortest, avoid highways, public transport)
- Payment Processing - Different payment methods (credit card, PayPal, cryptocurrency)
- Compression Algorithms - Various compression strategies (ZIP, RAR, 7z)
- Sorting Algorithms - Different sorting implementations based on data characteristics
Observer Pattern
Section titled “Observer Pattern”Key Components
Section titled “Key Components”- Subject: Maintains a list of observers and notifies them of state changes
- Observer: Interface that defines the update method for objects that should be notified
- ConcreteObserver: Implements the Observer interface to respond to updates
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- UI Event Listeners - Button clicks, form submissions, keyboard events
- Subscription Systems - YouTube channels, newsletters, RSS feeds
- Stock Market Feeds - Real-time price updates to multiple traders
- Social Media - Notification systems for likes, comments, and shares
Command Pattern
Section titled “Command Pattern”Key Components
Section titled “Key Components”- Command - Interface with an execute method
- ConcreteCommand - Implements Command and links to a Receiver
- Invoker - Asks the command to carry out the action
- Receiver - Knows how to perform the operations
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- Remote Controls - TV remotes, smart home devices
- Text Editors - Undo/redo functionality
- Game Commands - Action queues, replay systems
- Task Schedulers - Job queues, batch processing
- Transactional Systems - Database transactions with rollback
Iterator Pattern
Section titled “Iterator Pattern”Key Components
Section titled “Key Components”- Iterator: Interface with methods for traversing a collection
- ConcreteIterator: Implements the Iterator interface
- Collection: Interface that creates an Iterator
- ConcreteCollection: Implements Collection and returns ConcreteIterator
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- Java Collections - Iterator and Iterable interfaces
- Database Result Sets - Cursor-based record traversal
- File Systems - Directory tree traversal
- Social Media Feeds - Infinite scroll pagination
State Pattern
Section titled “State Pattern”Key Components
Section titled “Key Components”- Context: Maintains a reference to a State object and delegates state-specific behavior
- State: Interface defining state-specific behavior
- ConcreteState: Classes that implement specific states’ behavior
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- Order Processing - States: ordered → paid → shipped → delivered
- Document Workflow - States: draft → review → approved → published
- Media Players - States: playing, paused, stopped, buffering
- TCP Connections - States: closed, listen, established, closing
- Vending Machines - States: idle, selecting, dispensing, out of stock
Chain of Responsibility Pattern
Section titled “Chain of Responsibility Pattern”Key Components
Section titled “Key Components”- Handler: Abstract class/interface defining the request handling method and successor link
- ConcreteHandler: Implements the request handling behavior
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- HTTP Middleware - Authentication → logging → compression → response
- Event Propagation - UI event bubbling in DOM hierarchy
- Approval Workflows - Employee → manager → director → VP
- Exception Handling - Try-catch chains in error processing
- Logging Frameworks - Different log levels (debug, info, warn, error)
Template Method Pattern
Section titled “Template Method Pattern”Key Components
Section titled “Key Components”- AbstractClass: Defines template methods and abstract operations
- ConcreteClass: Implements the primitive operations required by the template method
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- Framework Lifecycle - React component lifecycle, Spring bean lifecycle
- Data Processing - ETL pipelines (extract → transform → load)
- Document Generation - Report templates with customizable sections
- Testing Frameworks - setUp → test → tearDown
- Game Development - Game loop: initialize → update → render
Visitor Pattern
Section titled “Visitor Pattern”Key Components
Section titled “Key Components”- Visitor: Interface declaring visit methods for each element type
- ConcreteVisitor: Implements the visitor interface with specific behavior
- Element: Interface declaring an accept method
- ConcreteElement: Implements the element interface
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- Compiler Design - Abstract syntax tree (AST) traversal and analysis
- Document Processing - XML/HTML DOM operations (rendering, validation, transformation)
- Report Generation - Different export formats (PDF, HTML, JSON) from same data structure
- Tax Calculation - Computing taxes for different product types
- Graphics Rendering - Rendering different shape types
Mediator Pattern
Section titled “Mediator Pattern”Key Components
Section titled “Key Components”- Mediator: Interface defining communication method between colleagues
- ConcreteMediator: Implements Mediator and coordinates between colleague objects
- Colleague: Abstract class for objects that communicate through the mediator
- ConcreteColleague: Implements Colleague with specific behavior
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- Air Traffic Control - Centralized coordination of aircraft communication
- Chat Rooms - Server mediates messages between users
- UI Dialog Boxes - Coordinating interactions between form elements
- Stock Exchange - Mediating trades between buyers and sellers
- Smart Home Systems - Central hub coordinating device interactions
Memento Pattern
Section titled “Memento Pattern”Key Components
Section titled “Key Components”- Originator: Creates a memento containing its state and uses it to restore state
- Memento: Stores the internal state of the Originator
- Caretaker: Keeps track of multiple mementos
When to Use
Section titled “When to Use”Real-World Examples
Section titled “Real-World Examples”- Text Editors - Undo/redo functionality for document changes
- Video Games - Save game states, checkpoints
- Database Systems - Transaction rollback mechanisms
- Version Control - Saving and restoring file states
- Drawing Applications - History of drawing operations
- Form Wizards - Saving progress across multiple steps