Dynamic Behavior

Intent: Make the behavior of an object dynamic.

Motivation

Dynamic behavior is a common objective in behavioral design patterns. The Observer, Chain of Responsibility, Strategy, and State design patterns are all examples. The structures of these design patterns all involve a delegation substructure that we can treat as a Dynamic Behavior design super-pattern.

Dynamic Behavior involves a Delegator participant and a Delegatee participant, with the Delegator delegating part of its responsibility to the Delegatee. Dynamic Behavior enhances flexility and easy reuse in several contexts, including

Structure

In any delegation the Delegator needs a variable to reference the Delegatee. In a typed OOL this variable must have a type, which we call Delegatee. To achieve the flexibility goals of this super-pattern, Delegatee just defines a common interface for a variety of concrete classes that implement different behaviors. We refer to these concrete classes as ConcreteDelegatees, as shown in the diagram below.

Strategy

Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Participants

  • Delegator - Context
  • Delegatee - Strategy
  • ConcreteDelegatee - ConcreteStrategyA, ...

Examples: Swing LayoutManager and LayoutManager2.

State

Intent: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Participants

  • Delegator - Context
  • Delegatee - State
  • ConcreteDelegatee - ConcreteStateA, ...

Examples: network connections.

Observer

Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Participants

  • Delegator - Subject
  • Delegatee - Observer
  • ConcreteDelegatee - ConcreteObserver

Examples: Swing listeners.

Chain of Responsibility

Intent: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Participants

  • Delegator - Handler
  • Delegatee - Handler
  • ConcreteDelegatee - ConcreteHandler1, ...

The association between Client and Handler is often a delegation-based pattern but it is not strictly speakin part of the Chain of Responsibility pattern. It is often either part of a Strategy or Observer pattern.

Examples: in classless OOLs inheritance may be implemented using a Chain of Responsibility pattern. Styled documents often use a Chain of Responsibility to implement style inheritance.