Skip to content

Behavioural Patterns

Behavioral patterns take care of effective communication and the assignment of responsibilities between objects.

PatternPurpose
StrategyDefine a family of algorithms, put each in a separate class, and make their objects interchangeable
ObserverDefine a subscription mechanism to notify multiple objects about events happening to observed objects
CommandTurn requests into stand-alone objects containing all request information
IteratorTraverse elements of a collection without exposing the underlying representation
StateLet an object alter its behavior when its internal state changes
Chain of ResponsibilityPass requests along a chain of handlers where each decides to process or forward
Template MethodDefine the skeleton of an algorithm in a superclass, letting subclasses override specific steps
VisitorSeparate algorithms from the objects on which they operate
MediatorReduce chaotic dependencies by forcing objects to collaborate through a mediator
MementoStore and restore the previous state of an object without revealing implementation details

PlantUML Diagram
  • 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
  • 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

PlantUML Diagram
  • 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
  • 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

PlantUML Diagram
  • 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
  • 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

PlantUML Diagram
  • 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
  • Java Collections - Iterator and Iterable interfaces
  • Database Result Sets - Cursor-based record traversal
  • File Systems - Directory tree traversal
  • Social Media Feeds - Infinite scroll pagination

PlantUML Diagram
  • 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
  • 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

PlantUML Diagram
  • Handler: Abstract class/interface defining the request handling method and successor link
  • ConcreteHandler: Implements the request handling behavior
  • 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)

PlantUML Diagram
  • AbstractClass: Defines template methods and abstract operations
  • ConcreteClass: Implements the primitive operations required by the template method
  • 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

PlantUML Diagram
  • 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
  • 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

PlantUML Diagram
  • 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
  • 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

PlantUML Diagram
  • 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
  • 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