Photo by Denisse Leon on Unsplash

Behavioral Patterns — overview

Daniel Jankowski
Netcompany
Published in
6 min readDec 12, 2019

--

These articles are a part of the design pattern series I’m writing to teach developers how to write clean and readable code that scale.

The main overview page can be found here .

These patterns describe ways of communication between objects to increase flexibility.

Topics I’ll cover:

  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Observer
  • State
  • Strategy

Chain of Responsibility

It is used to pass tasks in a chain of objects. The object checks the task and decides whether to invoke it or not. If not, the task is passed along the chain to the next object

The main problem is that sometimes the task will not executed by handlers.

Example below show you simple way to use this design pattern.

You can see interface ‘IHandler’, abstract class ‘HandlerBase’ and other classes: ‘HandlerMessage’, ‘HandlerSubject’,‘HandlerSound’ and enum ‘TaskKind’.
Here’s how you can use it:

The result is:

Message: Hi
Subject: This is very important
It only plays sound

You can see that the system failed to handle recent call:

handlerMessage.RunTask(TaskKind.Other);

This is because there is no handler to handle this one (‘TaskKind.Other’).
A very good example would be events in browser or in winforms. If you click the button on the form, event is propagating from button, to owner’s button for example to the form. Each object can handle the click.

Command

The main purpose of this pattern is to store all data needed to perform compliance. It is very important when you need to reproduce invoked commands or back in time.

We have a separate code for sending requests and a code receiving these requests. It gives us more flexible code.

Here a simple schema about this solution:

The program can look like this one:

The result is:

Kitchen prepared the meal for 4

Interpreter

Interpreter Design Pattern is very simple to understand in my mind. If you need to transform values, you can use this pattern. A simple example would be converting Arabic numbers to Roman ones or binary.

Simple diagram for it:

Observer

It observes the state of one object and when it changes, it sends information to all objects registered as observers to call the method
updating them. Observers delegate responsibility for monitoring the event
to the main class.

Observer

When the state was changed, the ‘Observable’ invoke the update function on all connected observers.

Here’s an example:

Now, let’s use it:

Result from this source code:

Observer name: Observer 1, counter: 1
Observer name: Observer 2, counter: 1
Observer name: Observer 3, counter: 1

Mediator

Mediator Design Pattern is usually used when there are many objects with compatible interfaces. The mediator is in the middle between all these objects and has references to other objects. It manages communication between them because it knows the scope of responsibility of all connected objects.

Mediator and Observer have a similar goal. The difference between them is that Observer distributes communication, while Mediator is responsible for communication between systems.

Think about it as a flight control tower.
All planes have to communicate with the flight control tower.

Photo by Miguel Ángel Sanz on Unsplash

Here’s a simple example of how a ‘Mediator’ can mediate when sending messages.

Colleague
Mediator

Source code below:

Sample:

Result:

[Colleague 1] received message: Very funny joke. from Colleague 2
[Colleague 3] received message: Very funny joke. from Colleague 2

Object the ‘Colleague’ has reference to the ‘Mediator’. When a ‘Colleague’ wants to send message to other objects, it calls function ‘SendMessage’ which uses Mediator’s interface. ‘Colleague’ uses ‘Mediator’ to disseminate message.

State

Photo by Rodion Kutsaev on Unsplash

The status pattern should be easy to understand. When you think about things around you, you can see that each thing always has a state. For instance a light bulb has two states, the light is either on or off. The tea in glass is hot or cold. The cars outside are driving or they are stopped. The same also applies to objects. The state in which the object changes its behavior.

The advantages of using this pattern include the ability to to easily expand the solution.

Here’s an example of the Status Design Pattern using a Car Engine. An engine has two states; on or off. If you want to drive, the engine needs to be turned on.

Function ‘CheckEngineSpeed’ is responsible for displaying the actual speed. While the function ‘StopDrive’ is responsible for reducing the speed down to zero.

Result:

Engine speed: 0 // before drive
Engine speed: 10 // after drive — state: Start
Engine speed: 20 // increase speed, after DriveFaster
Engine speed: 30 // increase speed, after DriveFaster
Engine speed: 0 // after StopDrive

Strategy

Photo by O12 on Unsplash

Strategy Design Pattern enables the selection of an appropriate algorithm at the application stage. You can think about how to choose a transportation for the trip. For example you may choose a bike, sometimes a car or a bus. Other times you just go on foot.

In my example I prepared four classes. Three describes how you can transport from one place to another — a ‘Car’, a ‘Boat’, a ‘Foot’. Last called Trip. Image that you are on the trip and first part of this trip, you have to go by car, than go on foot to the boat. The last part you swim in a boat.

Take an example below:

Program:

Result:

Transport by Car
Transport by Foot
Transport by Boat

Summary

Behavioral Patterns correspond to communication between objects. It describes not only the structure of classes but it focus on the patterns of communication between them.

I invite you to read the other articles in this series:

You can follow/contact me through this link: Daniel Jankowski.

This article is the property of Netcompany.

Netcompany provides IT solutions for both large enterprises and governments

--

--

Netcompany
Netcompany

Published in Netcompany

Vi brenner for å lære og dele det vi kan med hverandre — her gir vi deg et lite innblikk i det vi kan og er nysgjerrig på! Alt fra teknologi, systemarkitektur og kode til design, metodikk og prosjektledelse.

Daniel Jankowski
Daniel Jankowski

Written by Daniel Jankowski

Senior Consultant @ Netcompany.