Behavioural software patterns

These patterns cover algorithms and the assignment of responsibilities between objects.

Iterator – this pattern is concerned with allowing iterative access to a composition without exposing the underlying implementation.

Typically an iterator is an abstract interface and the composite object creates a concrete iterator that implements it – but the iterator interface is what is used by other objects.

Mediator – the mediator pattern is concerned with ensuring loose coupling between objects by defining interfaces that allow them to interact without knowledge of each others’ internals.

Observer – this pattern defines a one-many dependency in which one object – called the subject – notifies subscribing objects of changes in its state.

UML to describe the Observer pattern
From Wikipedia

State – this pattern is about allowing an object to change its behaviour when its state changes. The object will appear to change its class.

The Gang of Four give the example of a TCP connection – which will respond differently to datagrams depending if it is in the LISTEN, ESTABLISHED or CLOSED state. In each of these cases a different subclass will handle behaviour, though a common interface is used by all three.

UML for state pattern
From Wikipedia

Strategy – this pattern allows objects with different algorithms to operate through a common interface. Typical examples in text books and lecture notes are including paper aeroplanes and rubber ducks in collections of aircraft and avians!

So, for instance, all aircraft may have a fly() method in their abstract interface, but the concrete implementation for the paper aeroplane implements behaviour appropriate for that type of craft.

UML for strategy pattern
From wikipedia

Template Method  – this pattern creates a skeleton for an algorithm but allows subclasses to over-ride specific parts.

Template method UML Class Diagram
Image via Wikipedia

Visitor – the visitor software pattern is concerned with allowing new algorithms to be applied to an object without changing the object itself. Instead a new visitor class implements the visitor interface. In this way many new methods can be dynamically added to a class.

Class Diagram for the Visitor Pattern
Image via Wikipedia

2 responses to “Behavioural software patterns”

  1. Very good post, Adrian.

    I would add to this that patterns like dependency injection, or Inversion of Control, are very good complements to these patterns that you have mentioned.

    The inclusion of IoC would allow to introduce new components holding new abstract classes that implement existing interfaces, so your “old” code will be able to learn “new” tricks without the need of a recompile.

    Kind regards, Gastón

  2. A correction to my previous post: where is says “holding new abstract classes”, it should say “holding new concrete classes”.

    I’m sorry for the error.

    Kind regards, Gastón