Programming Search⌘K

Conceptcore

Behavioral pattern

Also called behavioral patterns, behavioural pattern, behavioral design pattern, class behavioral pattern, object behavioral pattern.

A behavioral pattern is a design pattern about algorithms and the communication between objects. Most of them put a behaviour that varies into its own object.

Applies to
core-languages

Idea

A program is not only a set of objects. The objects work together, and the way they divide the work decides what can change later. A behavioral pattern is a software design pattern for collaboration between objects.1 Most behavioral design patterns are specifically concerned with communication between objects.2

Design Patterns names two kinds. A class behavioral pattern uses inheritance to divide the behaviour between classes. An object behavioral pattern uses object composition: one object holds another object that does a part of the work.3 Template Method uses inheritance, and Strategy uses composition.1

class Checkout:  # class pattern: Template Method
    def total(self, prices):
        return self.discount(sum(prices))

    def discount(self, amount):
        return amount


class SaleCheckout(Checkout):
    def discount(self, amount):  # the subclass gives the step
        return amount * 9 // 10


class Till:  # object pattern: Strategy
    def __init__(self, discount):
        self.discount = discount

    def total(self, prices):
        return self.discount(sum(prices))


prices = [40, 60]
print("class pattern:", SaleCheckout().total(prices))
till = Till(lambda amount: amount * 9 // 10)
print("object pattern:", till.total(prices))
till.discount = lambda amount: amount - 20  # change it while the program runs
print("changed at run time:", till.total(prices))
Output
class pattern: 90
object pattern: 90
changed at run time: 80

The class pattern fixes the discount when the program creates the object. The object pattern can change it later, because the discount is a separate value.

How it works

The eleven behavioral patterns of Design Patterns are Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method and Visitor.2 Interpreter and Template Method are class patterns. The other nine are object patterns.3

Most of them use one of a few moves:3

  • Encapsulate what varies. Put a behaviour that can change into its own object. Strategy holds an algorithm, State holds the behaviour for one state, Iterator holds a way to go through a collection, and Command holds a request.2
  • Pass objects as arguments. A visitor is passed to each element of a structure. A command or a memento is a value that one part of the program gives to another.3
  • Decouple senders and receivers. Observer lets a number of observer objects see an event.2 Chain of Responsibility passes a request along a chain of processing objects.2 Mediator is the only class that has detailed knowledge of the methods of the others.2

Later lists add patterns that are not in the book, such as Blackboard, Null object, Publish-subscribe and Specification.1

In languages

LanguageVerdictNote
PythonNative
C++Idiom
JavaIdiom
CIdiomA function pointer with a context pointer is a strategy or a callback, and a switch on a type tag takes the place of a visitor.
C#Idiom
JavaScriptNative
TypeScriptNative
GoIdiom
RustIdiom
KotlinNativeFunction types and lambdas make a strategy or a command a value, and a when expression on a sealed class can take the place of a visitor; no example is executed here because the test image has no kotlinc.
SQLDoes not applyA query is declarative, so there are no objects that divide the work.
BashIdiomThe name of a function can be passed as a string and called later, which is a simple strategy or command.
PowerShellIdiomA script block is a value that can be stored and invoked later, which is a strategy or a command; no example is executed here because the test image has no pwsh.
HTMLDoes not applyMarkup has no behaviour of its own.
CSSDoes not applyStyle rules have no objects or algorithms.
Regular expressionsDoes not applyA pattern has no objects or behaviour to vary.
Language Verdict Mechanism
Python native functions are values, so a strategy, a command or a callback is a function; generators for iterators; match for visitors
JavaScript native functions are values; iterators and generators; events for observers
TypeScript native function types; discriminated unions with exhaustive checks in place of visitors
Java idiom interfaces and lambdas for functional interfaces; Iterator; pattern matching for switch on sealed types
C# idiom delegates and lambdas; events for observers; IEnumerable and yield return; switch expressions
C++ idiom virtual functions; std::function and lambdas; iterators; std::variant with std::visit
Go idiom function values and interfaces; type switches; channels between goroutines
Rust idiom traits and closures; the Iterator trait; enums with exhaustive match in place of visitors
Kotlin native function types and lambdas; sealed classes with exhaustive when
C idiom function pointers with a context pointer; switch on a type tag
Bash idiom a function name passed as a string and called later
PowerShell idiom script blocks as values that are invoked later
SQL n/a a query is declarative, so there are no objects that divide the work
Regex n/a a pattern has no objects or behaviour to vary
HTML n/a markup has no behaviour of its own
CSS n/a style rules have no objects or algorithms

Many behavioral patterns become simpler in languages with first-class functions. Norvig lists Command, Strategy, Template Method and Visitor among the patterns that first-class functions make invisible or simpler. He lists State and Chain of Responsibility under first-class types, Interpreter and Iterator under macros, and Mediator and Observer under method combination.4

Sum types with exhaustive matching are a second replacement for Visitor. The arms of a Rust match must cover all possibilities.5 A Kotlin when expression with a sealed class lets the compiler check that all possible cases are covered.6 TypeScript uses narrowing and the never type to do exhaustive checking in a switch statement.7 Java 21 has pattern matching for switch expressions and statements.8

The example files show the program of the Idea section in each language: a class pattern with a subclass, and an object pattern with a function value.

PythonGitHub
from typing import Callable


class Checkout:
    def total(self, prices: list[int]) -> int:
        return self.discount(sum(prices))

    def discount(self, amount: int) -> int:
        return amount


class SaleCheckout(Checkout):
    def discount(self, amount: int) -> int:
        return amount * 9 // 10


class Till:
    def __init__(self, discount: Callable[[int], int]) -> None:
        self.discount = discount

    def total(self, prices: list[int]) -> int:
        return self.discount(sum(prices))


prices = [40, 60]
print("class pattern:", SaleCheckout().total(prices))
till = Till(lambda amount: amount * 9 // 10)
print("object pattern:", till.total(prices))
till.discount = lambda amount: amount - 20
print("changed at run time:", till.total(prices))
Output
class pattern: 90
object pattern: 90
changed at run time: 80
  • Verdict: native. A function is a value, so the strategy is a lambda and no strategy class is needed. The class pattern uses an ordinary method override.
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>

class Checkout {
public:
    virtual ~Checkout() = default;
    int total(const std::vector<int>& prices) const {
        return discount(std::accumulate(prices.begin(), prices.end(), 0));
    }
protected:
    virtual int discount(int amount) const { return amount; }
};

class SaleCheckout : public Checkout {
protected:
    int discount(int amount) const override { return amount * 9 / 10; }
};

struct Till {
    std::function<int(int)> discount;
    int total(const std::vector<int>& prices) const {
        return discount(std::accumulate(prices.begin(), prices.end(), 0));
    }
};

int main() {
    std::vector<int> prices{40, 60};
    std::cout << "class pattern: " << SaleCheckout{}.total(prices) << "\n";
    Till till{[](int amount) { return amount * 9 / 10; }};
    std::cout << "object pattern: " << till.total(prices) << "\n";
    till.discount = [](int amount) { return amount - 20; };
    std::cout << "changed at run time: " << till.total(prices) << "\n";
}
Output
class pattern: 90
object pattern: 90
changed at run time: 80
  • Verdict: idiom. The class pattern uses a virtual function. The strategy is a std::function that holds a lambda.
JavaGitHub
import java.util.List;
import java.util.function.IntUnaryOperator;

public class Main {
    static abstract class Checkout {
        int total(List<Integer> prices) {
            return discount(prices.stream().mapToInt(Integer::intValue).sum());
        }
        abstract int discount(int amount);
    }

    static class SaleCheckout extends Checkout {
        int discount(int amount) { return amount * 9 / 10; }
    }

    static class Till {
        IntUnaryOperator discount;
        Till(IntUnaryOperator discount) { this.discount = discount; }
        int total(List<Integer> prices) {
            return discount.applyAsInt(prices.stream().mapToInt(Integer::intValue).sum());
        }
    }

    public static void main(String[] args) {
        List<Integer> prices = List.of(40, 60);
        System.out.println("class pattern: " + new SaleCheckout().total(prices));
        Till till = new Till(amount -> amount * 9 / 10);
        System.out.println("object pattern: " + till.total(prices));
        till.discount = amount -> amount - 20;
        System.out.println("changed at run time: " + till.total(prices));
    }
}
Output
class pattern: 90
object pattern: 90
changed at run time: 80
  • Verdict: idiom. The strategy has the functional interface type IntUnaryOperator, and a lambda gives its one method.
using System;
using System.Linq;

abstract class Checkout
{
    public int Total(int[] prices) => Discount(prices.Sum());
    protected abstract int Discount(int amount);
}

class SaleCheckout : Checkout
{
    protected override int Discount(int amount) => amount * 9 / 10;
}

class Till
{
    public Func<int, int> Discount;
    public Till(Func<int, int> discount) { Discount = discount; }
    public int Total(int[] prices) => Discount(prices.Sum());
}

static class Program
{
    static void Main()
    {
        int[] prices = { 40, 60 };
        Console.WriteLine("class pattern: " + new SaleCheckout().Total(prices));
        var till = new Till(amount => amount * 9 / 10);
        Console.WriteLine("object pattern: " + till.Total(prices));
        till.Discount = amount => amount - 20;
        Console.WriteLine("changed at run time: " + till.Total(prices));
    }
}
Output
class pattern: 90
object pattern: 90
changed at run time: 80
  • Verdict: idiom. The strategy is a delegate of type Func<int, int>, and a lambda creates it. The class pattern uses an abstract method and override.
JavaScriptGitHub
class Checkout {
  total(prices) {
    return this.discount(prices.reduce((a, b) => a + b, 0));
  }
  discount(amount) {
    return amount;
  }
}

class SaleCheckout extends Checkout {
  discount(amount) {
    return Math.floor((amount * 9) / 10);
  }
}

class Till {
  constructor(discount) {
    this.discount = discount;
  }
  total(prices) {
    return this.discount(prices.reduce((a, b) => a + b, 0));
  }
}

const prices = [40, 60];
console.log("class pattern:", new SaleCheckout().total(prices));
const till = new Till((amount) => Math.floor((amount * 9) / 10));
console.log("object pattern:", till.total(prices));
till.discount = (amount) => amount - 20;
console.log("changed at run time:", till.total(prices));
Output
class pattern: 90
object pattern: 90
changed at run time: 80
  • Verdict: native. Functions are values, so the strategy is an arrow function that the till stores in a field.
TypeScriptGitHub
type Discount = (amount: number) => number;

const sum = (prices: number[]): number => prices.reduce((a, b) => a + b, 0);

abstract class Checkout {
  total(prices: number[]): number {
    return this.discount(sum(prices));
  }
  protected abstract discount(amount: number): number;
}

class SaleCheckout extends Checkout {
  protected discount(amount: number): number {
    return Math.floor((amount * 9) / 10);
  }
}

class Till {
  discount: Discount;
  constructor(discount: Discount) {
    this.discount = discount;
  }
  total(prices: number[]): number {
    return this.discount(sum(prices));
  }
}

const prices = [40, 60];
console.log("class pattern:", new SaleCheckout().total(prices));
const till = new Till((amount) => Math.floor((amount * 9) / 10));
console.log("object pattern:", till.total(prices));
till.discount = (amount) => amount - 20;
console.log("changed at run time:", till.total(prices));
Output
class pattern: 90
object pattern: 90
changed at run time: 80
  • Verdict: native. The type Discount is a function type, so the compiler checks every strategy that is given to the till. The step of the class pattern is an abstract method.
package main

import "fmt"

// Go has no inheritance, so the "class" form embeds a step interface.
type Step interface{ Discount(amount int) int }

type Checkout struct{ step Step }

func (c Checkout) Total(prices []int) int {
	sum := 0
	for _, p := range prices {
		sum += p
	}
	return c.step.Discount(sum)
}

type Sale struct{}

func (Sale) Discount(amount int) int { return amount * 9 / 10 }

type Till struct{ discount func(int) int }

func (t Till) Total(prices []int) int {
	sum := 0
	for _, p := range prices {
		sum += p
	}
	return t.discount(sum)
}

func main() {
	prices := []int{40, 60}
	fmt.Println("class pattern:", Checkout{Sale{}}.Total(prices))
	till := Till{func(amount int) int { return amount * 9 / 10 }}
	fmt.Println("object pattern:", till.Total(prices))
	till.discount = func(amount int) int { return amount - 20 }
	fmt.Println("changed at run time:", till.Total(prices))
}
Output
class pattern: 90
object pattern: 90
changed at run time: 80
  • Verdict: idiom. Go has no subclasses, so the step of the first form is an interface value that the checkout holds. The strategy is a function value.
RustGitHub
trait Checkout {
    fn discount(&self, amount: i32) -> i32 {
        amount
    }
    fn total(&self, prices: &[i32]) -> i32 {
        self.discount(prices.iter().sum())
    }
}

struct SaleCheckout;

impl Checkout for SaleCheckout {
    fn discount(&self, amount: i32) -> i32 {
        amount * 9 / 10
    }
}

struct Till {
    discount: Box<dyn Fn(i32) -> i32>,
}

impl Till {
    fn total(&self, prices: &[i32]) -> i32 {
        (self.discount)(prices.iter().sum())
    }
}

fn main() {
    let prices = [40, 60];
    println!("class pattern: {}", SaleCheckout.total(&prices));
    let mut till = Till { discount: Box::new(|amount| amount * 9 / 10) };
    println!("object pattern: {}", till.total(&prices));
    till.discount = Box::new(|amount| amount - 20);
    println!("changed at run time: {}", till.total(&prices));
}
Output
class pattern: 90
object pattern: 90
changed at run time: 80
  • Verdict: idiom. Rust has no inheritance. A trait with a default method takes the place of the base class, and the type overrides one step. The strategy is a boxed closure.
  • Creational and structural patterns. Design Patterns sorts its 23 patterns by purpose into creational, structural and behavioral groups.3 Structural patterns are about how objects are composed, and behavioral patterns are about how the composed objects divide the work.
  • Concurrency patterns. The article on behavioral patterns links to concurrency patterns, creational patterns and structural patterns as related groups.1
  • Functional forms. A strategy or a command can be a function, and a visitor can be a match on a sum type.45

Pitfalls

  • Pattern for its own sake. A function value is often enough where a class hierarchy was written for one varying step.4
  • Hidden flow of control. With Observer or Chain of Responsibility, the code that sends a request does not show which code handles it.
  • Changes during notification. An observer that unsubscribes while the subject notifies can break the loop. Code that modifies a collection while iterating over that same collection can be tricky to get right.9 Here observer b is skipped:

This code runs but gives a wrong answer on purpose.

class Subject:
    def __init__(self):
        self.observers = []

    def notify(self):
        for o in self.observers:  # iterates the list that changes
            o(self)


subject = Subject()


def make(name, once=False):
    def observer(s):
        print(name, "notified")
        if once:
            s.observers.remove(observer)
    return observer


subject.observers += [make("a", once=True), make("b"), make("c")]
subject.notify()
Output
a notified
c notified

The fix is to loop over a copy: for o in list(self.observers).9

Cost

Each object pattern adds one call through an interface or a function value. In most programs this is small next to the work of the call. The larger cost is in reading: the behaviour is in more places, and a reader must find which object is in use at run time.

History

Design Patterns, by Gamma, Helm, Johnson and Vlissides, appeared in 1994. It classified 23 patterns by purpose and scope, and its behavioral group has eleven patterns.32

Peter Norvig presented Design Patterns in Dynamic Programming at Object World on May 5, 1996. He found that 16 of the 23 patterns are invisible or simpler in Dylan or Lisp, for at least some uses of each pattern.4 Ten of the eleven behavioral patterns are in his list. Memento is not.4

References

  1. Behavioral pattern, Wikipedia, Introduction; Examples
  2. Design Patterns, Wikipedia, Patterns by type, Behavioral
  3. Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 1, Organizing the Catalog (Table 1.1); Chapter 5, Behavioral Patterns, introduction and Discussion of Behavioral Patterns
  4. Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 5, 1996, slides 9 and 10
  5. The match Control Flow Construct, The Rust Programming Language, Matches Are Exhaustive
  6. Sealed classes and interfaces, Kotlin documentation, Use sealed classes with when expression
  7. Narrowing, TypeScript Handbook, Discriminated unions; Exhaustiveness checking
  8. JEP 441, Pattern Matching for switch, Summary; Release
  9. More Control Flow Tools, The Python Tutorial, 4.2 for Statements

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4T6Q62/text.yaml