Link Search Menu Expand Document

Behavioral Design Patterns

This tutorial is about “Behavioral Design Patterns” that suggests how to assign functional responsibilities between objects and how to use the solution methods required by the software.

First, we define behavioral design patterns. We explain when we use this kind of structure and then we describe frequently used behavioral patterns as follows: Mediator, State, Observer, Memento, Template Method, Command, Chain of Responsibility. Strategy, Interpreter, Visitor. In the last part, we summarize the tutorial.

Definition of Behavioral Design Patterns

Behavioral patterns present communication between objects. Behavioral patterns allow the designer to focus on communication between objects. Just like Structural patterns, they are divided into two: Class and Object types of behavioral patterns.

Class behavioral patterns make it possible to distribute behaviors across classes using inheritance. On the other hand, Object behavioral patterns make it possible to provide behaviors that can not be easily achieved with a single object by combining objects with an object group. We will explain 10 different situations and design patterns used in these situations.

Mediator

While applications grow, they contain many classes and hierarchies. The logic and data collections of the application are distributed to the classes. There is constant communication between these classes for the application to work.

As the number of classes increases, the dependencies between them increase and the application becomes more difficult to maintain and change. Here, the Mediator design pattern is used to reduce the dependencies between these classes and to facilitate communication between them.

State

The State design pattern can be used if the behavior of the object changes when its state changes. If we have objects behave differently in different situations, using this design pattern prevents the changing behavior of objects depending on their state from being controlled by complex “if/else” or “switch” statements.

Observer

This design pattern is used when there is a change in the state of an object and we want to notify these changes to other objects. In short, many objects that are in the position of listeners constantly observe the state of an object, and these observers are notified during a change.

Memento

It is a design pattern that allows an object to keep its state and then return to the state before the last action was performed. In other words, it provides a way to hide some states of the object and return to these situations when necessary.

Code example for Memento pattern is given below:

import java.util.List;
import java.util.ArrayList;

 
class Life
{
private String time;
 

public void set(String time)
{
System.out.println("Setting time to " + time);
this.time = time;

}

 
public Memento saveToMemento()
{
System.out.println("Saving time to Memento");
return new Memento(time);
}

 
public void restoreFromMemento(Memento memento)
{
time = memento.getSavedTime();
System.out.println("Time restored from Memento: " + time);
}

 
public static class Memento
{
private final String time;

 
public Memento(String timeToSave)
{
time = timeToSave;
}
 

public String getSavedTime()
{
return time;
}
}
}

 

class Design
{
 

public static void main(String[] args)
{

 

List<Life.Memento> savedTimes = new ArrayList<Life.Memento>();
 

Life life = new Life();
 

//time travel and record the eras
life.set("1000 B.C.");
savedTimes.add(life.saveToMemento());
life.set("1000 A.D.");
savedTimes.add(life.saveToMemento());
life.set("2000 A.D.");
savedTimes.add(life.saveToMemento());
life.set("4000 A.D.");
life.restoreFromMemento(savedTimes.get(0));
}
}

Output is:

Setting time to 1000 B.C.

Saving time to Memento

Setting time to 1000 A.D.

Saving time to Memento

Setting time to 2000 A.D.

Saving time to Memento

Setting time to 4000 A.D.

Time restored from Memento: 1000 B.C.

Template Method

The template Method is the top class in the class hierarchy. This top-class reveals the template that subclasses should follow, the subclasses determine the details themselves. Thanks to this design pattern, code repetitions in lower classes are avoided. The common codes of the lower classes are collected in one place in the upper class. When a change is needed in this common part, this is done at one point.

Command

The objects contain a function and the necessary parameters for that function. When some operations are performed by triggering these objects from the outside, the objects that will trigger the action and the objects that perform the action are separated from each other. Operations of the objects can be multiple and they can be stored in collections. New command objects can also be easily added when new functionality is requested.

Chain of Responsibility

This design pattern consists of a set of function classes and the command classes required to initialize those classes. Function classes keep what kind of work they do, and also determine what another function class in the array will be. This design pattern can be used when a process needs to go through a certain amount of functions sequentially.

Strategy

In cases where different methods are applicable for an operation, the object chooses which method to apply. With this design pattern, the details of how the method should be applied are separated from the object that will use this method. Also, by using this design pattern, the code is extracted from long “if/else” or “switch” statements.

Interpreter

The purpose of this design pattern is to interpret a specialized computer language. The main idea is to create a separate class for each symbol of this specialized language. This design pattern can be used to interpret SQL-style languages in database management systems.

Visitor

This design pattern is used to operate on many and different types of objects. No changes are made to the objects. Visitor objects do the process. If new objects are not added to the system, but new operations need to be added frequently, this design pattern can be used. The codes related to the action are gathered in a central object.

Summary

In this tutorial, we define the Behavioral Design Patterns at the start. Then we give some examples of behavioral patterns. The first one is the “Mediator” which enables the creation of a family of objects on different platforms with a single interface.

After that, we mention “State”, which is a structure based on creating a class. Then we describe the “Observer” pattern that allows a group of objects to automatically be aware of changes in an object under observation.

Next, we mention the “Memento” pattern that is used to keep the states of objects that play important roles in the application and to return the objects to their previous state when necessary. The “Template Method” pattern enables us to create new objects by sampling from existing ones, rather than creating them from scratch. The “Command” pattern makes it possible to process user requests by converting them into objects.

The “Chain of Responsibility” pattern allows user requests to be evaluated and fulfilled by more than one object. “Strategy” pattern regulates the situations in which a transaction can be performed in more than one way. “Interpreter” pattern manipulates pseudo-language defined to fulfill the requirements of complex applications.

Finally, the “Visitor” pattern allows new transactions to be added to a compound structure. The visitor visits the objects in the object compound structure one by one, collects and processes the necessary information, and presents them to the user.

Other useful articles:


Back to top

© , Java Interviews — All Rights Reserved - Terms of Use - Privacy Policy