Behavioral Patterns «Prev Next»

Lesson 2 What is a behavioral pattern?
Objective Define Behavioral Patterns

What is a Behavioral Design Pattern?

A behavioral design pattern explains how objects interact: how they send messages to each other, how the steps of a task are divided among different objects, and how responsibilities are allocated across a system. Behavioral patterns identify common communication patterns between objects and provide proven solutions for implementing those patterns. By applying a behavioral pattern, you increase the flexibility of the communication between objects without having to redesign the objects themselves.

Understanding where behavioral patterns fit within the GoF taxonomy requires comparing them to the other two categories. The three GoF pattern categories each address a different concern:

  1. Creational patterns describe a moment in time: the instant of object creation. They control how objects are instantiated and which class is used.
  2. Structural patterns describe a more or less static structure: how classes and objects are composed to form larger structures.
  3. Behavioral patterns describe a process or a flow: how objects communicate and collaborate to carry out a task over time.

Behavioral patterns make up the largest GoF category. Eleven of the twenty-three GoF patterns are behavioral, reflecting how much of software design concerns itself with interaction and communication rather than structure or creation.

How Objects Interact Using Behavioral Patterns

A behavioral pattern describes how different objects and classes send messages to each other to accomplish a task and how the responsibilities for the steps of that task are divided. Five patterns illustrate the range of interaction problems behavioral patterns solve:

  • Mediator: objects communicate through a central mediator object rather than holding direct references to each other. The mediator reduces coupling by preventing objects from referring to each other explicitly, allowing their interaction to be varied independently.
  • Observer: when a subject object changes state, all registered observers are notified and updated automatically. The subject maintains a list of observers and calls a known method on each when its state changes. In modern Java, java.util.concurrent.Flow (Java 9+) provides the standard reactive Observer implementation, replacing the deprecated java.util.Observable.
  • Strategy: algorithms are encapsulated as interchangeable objects, allowing the algorithm to be selected and substituted at runtime without changing the client that uses it. In modern Java, a Comparator passed as a lambda expression to Collections.sort() is a Strategy.
  • Command: actions are encapsulated as command objects, decoupling the object that invokes the action from the object that knows how to perform it. Commands can be queued, logged, and reversed.
  • Iterator: elements of a collection are accessed sequentially without exposing the underlying representation. In modern Java, java.lang.Iterable and java.util.Iterator are the standard library implementations, and the enhanced for-each loop is built on this pattern.

Behavioral Class Patterns and Behavioral Object Patterns

GoF behavioral patterns divide into two subcategories based on whether they use inheritance or object composition as the primary mechanism:

  • Behavioral Class Patterns use inheritance, subclassing, and polymorphism to adjust the steps taken during a process. They focus on changing the exact algorithm used or task performed depending on circumstances by varying the class. The Template Method pattern is the primary example: it defines the skeleton of an algorithm in a superclass and lets subclasses override specific steps without changing the overall structure.
  • Behavioral Object Patterns describe how different objects work together to accomplish a task. They accomplish tasks that would be difficult or impossible with single objects and make the overall flow simpler, more understandable, and more robust than ad hoc solutions assembled without a coherent design. Observer, Mediator, Chain of Responsibility, Command, Iterator, Strategy, State, Memento, and Visitor are all behavioral object patterns.

GoF Behavioral Patterns

The Gang of Four defined eleven behavioral patterns. These form the core behavioral pattern catalog:

  1. Chain of Responsibility: command objects are handled or passed on to other objects by logic-containing processing objects. Each handler decides whether to process the request or pass it along the chain.
  2. Command: command objects encapsulate an action and its parameters, decoupling the sender from the receiver and enabling queuing, logging, and undo support.
  3. Interpreter: implements a specialized language to rapidly solve a specific set of problems by defining a grammatical representation and providing an interpreter to evaluate sentences in that language.
  4. Iterator: iterators access the elements of an aggregate object sequentially without exposing its underlying representation. In Java, java.lang.Iterable and java.util.Iterator are the standard implementations.
  5. Mediator: provides a unified interface through which a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.
  6. Memento: provides the ability to restore an object to a previous state (rollback) by capturing and externalizing its internal state without violating encapsulation.
  7. Observer: also known as Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. When the subject's state changes, all registered observers are notified automatically. The modern Java replacement for the deprecated java.util.Observable is java.util.concurrent.Flow (Java 9+).
  8. State: a clean way for an object to alter its behavior when its internal state changes. The object appears to change its class.
  9. Strategy: algorithms can be selected interchangeably at runtime. In modern Java, functional interfaces and lambda expressions are the idiomatic Strategy implementation.
  10. Template Method: defines the skeleton of an algorithm in a superclass, letting subclasses override specific steps without changing the overall structure.
  11. Visitor: a way to separate an algorithm from the object structure it operates on, allowing new operations to be defined without changing the classes of the elements.

Extended Behavioral Patterns

Beyond the original GoF catalog, the software engineering community has identified additional behavioral patterns that address common problems not covered by the eleven GoF patterns. These community-recognized patterns follow the same pattern template (intent, applicability, structure, and consequences) but are not attributed to the Gang of Four:

  • Externalize the Stack: turns a recursive function into an iterative one that uses an explicit stack, avoiding stack overflow risks for deeply recursive structures.
  • Hierarchical Visitor: provides a way to visit every node in a hierarchical data structure such as a tree, extending the GoF Visitor pattern for recursive structures.
  • Null Object: acts as a default value of an object, implementing a do-nothing behavior that avoids null checks scattered throughout client code.
  • Specification: recombinable business logic expressed in a boolean fashion, originating in Domain-Driven Design. Specifications can be combined with and, or, and not operators.
  • Weak Reference: decouples an observer from an observable by holding a weak reference to the observer, allowing it to be garbage collected without requiring explicit deregistration.
  • Scheduled-task: schedules a task to be performed at a particular interval or clock time, used in real-time computing and background processing systems.
  • Single-serving Visitor: optimizes the implementation of a Visitor that is allocated, used only once, and then discarded, avoiding the overhead of a reusable visitor when the operation is performed once per traversal.

SEMrush Software 2 SEMrush Banner 2