0% found this document useful (0 votes)
21 views

08-Behavioral Design Patterns2

Uploaded by

Rr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

08-Behavioral Design Patterns2

Uploaded by

Rr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

BEHAVIORAL DESIGN PATTERNS 2

Software Design Patterns

FAKHRELDIN ALI
[email protected]
STRUCTURAL DESIGN PATTERNS

 Behavioral design patterns are concerned with algorithms and the


assignment of responsibilities between objects.

DESIGN PATTERNS 2
CHAIN OF RESPONSIBILITY DESIGN
PATTERN

Chain of Responsibility is a behavioral design pattern that lets you pass requests
along a chain of handlers. Upon receiving a request, each handler decides either to
process the request or to pass it to the next handler in the chain.

DESIGN PATTERNS 3
CHAIN OF RESPONSIBILITY DESIGN
PATTERN

• Imagine you’ve just bought and installed a new piece of hardware on your
computer. the computer has several operating systems installed. Windows
detects and enables the hardware automatically. Linux refuses to work with the
new hardware. you decide to call the tech-support phone number written on
the box.
• The first thing you hear is the robotic voice of the autoresponder. It suggests
nine popular solutions to various problems, none of which are relevant to your
case.
DESIGN After a while, the robot connects you to a live operator.
PATTERNS 4
CHAIN OF RESPONSIBILITY DESIGN
PATTERN

• The operator isn’t able to suggest anything specific either. You demand to be
connected to a proper engineer.

• The engineer tells you where to download proper drivers for your new
hardware and how to install them on Linux. Finally, the solution!

DESIGN PATTERNS 5
CHAIN OF RESPONSIBILITY DESIGN
PATTERN
Problem
Imagine that you’re working on an online ordering system.You want to restrict access
to the system so only authenticated users can create orders. Also, users who have
administrative permissions must have full access to all orders.
After a bit of planning, you realized that these checks must be performed sequentially.
The application can attempt to authenticate a user to the system whenever it receives
a request that contains the user’s credentials. However, if those credentials aren’t
correct and authentication fails, there’s no reason to proceed with any other checks.

DESIGN PATTERNS 6
CHAIN OF RESPONSIBILITY DESIGN
PATTERN
Solution

Like many other behavioral design patterns, the Chain of Responsibility relies on
transforming particular behaviors into stand-alone objects called handlers.
In our case, each check should be extracted to its own class with a single method
that performs the check. The request, along with its data, is passed to this method
as an argument.

The pattern suggests that you link these handlers into a chain. Each linked
handler has a field for storing a reference to the next handler in the chain. In
addition to processing a request, handlers pass the request further along the chain.
The request travels along the chain until all handlers have had a chance to process
it.
Here’s the best part: a handler can decide not to pass the request further down
the chain and effectively stop any further processing.
DESIGN PATTERNS 7
CHAIN OF RESPONSIBILITY DESIGN
PATTERN
In our example with ordering systems, a handler performs the processing and then
decides whether to pass the request further down the chain. Assuming the request
contains the right data, all the handlers can execute their primary behavior, whether
it’s authentication checks or caching.

DESIGN PATTERNS 8
CHAIN OF RESPONSIBILITY DESIGN
PATTERN

Applicability

• Use the Chain of Responsibility pattern when your program is expected to


process different kinds of requests in various ways, but the exact types
of requests and their sequences are unknown beforehand.

• Use the pattern when it’s essential to execute several handlers in a


particular order.

• Use the Chain of Responsibility pattern when the set of handlers and their
order are supposed to change at runtime.

DESIGN PATTERNS 9
CHAIN OF RESPONSIBILITY DESIGN
PATTERN

DESIGN PATTERNS 10
ITERATOR DESIGN PATTERN
Iterator is a behavioral design pattern that lets you traverse elements of a collection
without exposing its underlying representation (list, stack, tree, etc.).

DESIGN PATTERNS 11
ITERATOR DESIGN PATTERN

You plan to visit Rome for a few days and visit all of its main sights and attractions.
But once there, you could waste a lot of time walking in circles, unable to find even
the Colosseum.
On the other hand, you could buy a virtual guide app for your smartphone and
use it for navigation. It’s smart and inexpensive, and you could be staying at some
interesting places for as long as you want.
DESIGN PATTERNS 12
ITERATOR DESIGN PATTERN

A third alternative is that you could spend some of the trip’s budget and hire a local
guide who knows the city like the back of his hand. The guide would be able to
tailor the tour to your likings, show you every attraction and tell a lot of exciting
stories. That’ll be even more fun; but, more expensive, too.

All of these options—the random directions born in your head, the smartphone
navigator or the human guide—act as iterators over the vast collection of sights and
attractions located in Rome.
DESIGN PATTERNS 13
ITERATOR DESIGN PATTERN
Problem

Most collections store their elements in simple lists. However, some of them are
based on stacks, trees, graphs and other complex data structures.

But no matter how a collection is structured, it must provide some way of accessing
its elements so that other code can use these elements. There should be a way to
go through each element of the collection without accessing the same elements
over and over.
This may sound like an easy job if you have a collection based on a list. You just loop
over all of the elements. But how do you sequentially traverse elements of a complex
data structure, such as a tree? For example, one day you might be just fine with
depth-first traversal of a tree.Yet the next day you might require breadth-first
traversal. And the next week, you might need something else, like random access to
the tree elements.
DESIGN PATTERNS 14
ITERATOR DESIGN PATTERN

The same collection can be traversed in several different ways.

DESIGN PATTERNS 15
ITERATOR DESIGN PATTERN
Solution
The main idea of the Iterator pattern is to extract the traversal behavior of a
collection into a separate object called an iterator.

DESIGN PATTERNS 16

Iterators implement various traversal algorithms. Several iterator objects can


traverse the same collection at the same time.
ITERATOR DESIGN PATTERN
• In addition to implementing the algorithm itself, an iterator object encapsulates all
of the traversal details, such as the current position and how many elements are
left till the end. Because of this, several iterators can go through the same
collection at the same time, independently of each other.

• Usually, iterators provide one primary method for fetching elements of the
collection. The client can keep running this method until it doesn’t return anything,
which means that the iterator has traversed all of the elements.

• All iterators must implement the same interface. This makes the client code
compatible with any collection type or any traversal algorithm as long as there’s a
proper iterator. If you need a special way to traverse a collection, you just create a
new iterator class, without having to change the collection or the client.

DESIGN PATTERNS 17
ITERATOR DESIGN PATTERN
Applicability

• Use the Iterator pattern when your collection has a complex data structure
under the hood, but you want to hide its complexity from clients (either for
convenience or security reasons).

• Use the pattern to reduce duplication of the traversal code across your app.

• Use the Iterator when you want your code to be able to traverse different data
structures or when types of these structures are unknown beforehand.

DESIGN PATTERNS 18
ITERATOR DESIGN PATTERN

DESIGN PATTERNS 19
MEDIATOR DESIGN PATTERN
Mediator is a behavioral design pattern that lets you reduce complex
dependencies between objects. The pattern restricts direct communications
between the objects and forces them to collaborate only via a mediator object.

DESIGN PATTERNS 20
MEDIATOR DESIGN PATTERN
Pilots of aircraft that approach or depart the airport control area don’t communicate
directly with each other. Instead, they speak to an air traffic controller, who sits in a
tall tower somewhere near the airstrip. Without the air traffic controller, pilots would
need to be aware of every plane in the vicinity of the airport, discussing landing
priorities with a committee of dozens of other pilots.

DESIGN PATTERNS 21
MEDIATOR DESIGN PATTERN
Problem
Say you have a dialog for creating and editing customer profiles. It consists of various
form controls such as text fields, checkboxes, buttons, etc.

Some of the form elements may interact with others. For instance, selecting the “I
have a dog” checkbox may reveal a hidden text field for entering the dog’s name.
Another example is the submit button that has to validate values of all fields before
saving the data.

By having this logic implemented directly inside the code of the form elements you
make these elements’ classes much harder to reuse in other forms of the app. For
example, you won’t be able to use that checkbox class inside another form,
because it’s coupled to the dog’s text field. You can use either all the classes
involved in rendering the profile form, or none at all.
DESIGN PATTERNS 22
MEDIATOR DESIGN PATTERN
Solution
The Mediator pattern suggests that you should cease all direct communication
between the components which you want to make independent of each other.
Instead, these components must collaborate indirectly, by calling a special mediator
object that redirects the calls to appropriate components. As a result, the
components depend only on a single mediator class instead of being coupled to
dozens of their colleagues.

In our example with the profile editing form, the dialog class itself may act as the
mediator. Most likely, the dialog class is already aware of all of its sub-elements, so
you won’t even need to introduce new dependencies into this class.

DESIGN PATTERNS 23
MEDIATOR DESIGN PATTERN

DESIGN PATTERNS 24
MEDIATOR DESIGN PATTERN

Applicability

Use the Mediator pattern when it’s hard to change some of the classes because
they are tightly coupled to a bunch of other classes.

Use the pattern when you can’t reuse a component in a different program
because it’s too dependent on other components.

Use the Mediator when you find yourself creating tons of component subclasses
just to reuse some basic behavior in various contexts.

DESIGN PATTERNS 25
MEDIATOR DESIGN PATTERN

In object-oriented programming, a god


object (sometimes also called an
omniscient or all-knowing object) is
an object that references a large number
of distinct types, has too many unrelated
or uncategorized methods, or some
combination of both.[1] The god object is
an example of an anti-pattern and a code
smell.[2]

DESIGN PATTERNS 26
TEMPLATE METHOD DESIGN PATTERN

Template Method is a behavioral design pattern that defines the skeleton of an


algorithm in the superclass but lets subclasses override specific steps of the
algorithm without changing its structure.

DESIGN PATTERNS 27
TEMPLATE METHOD DESIGN PATTERN
The template method approach can be used in mass housing construction. The
architectural plan for building a standard house may contain several extension
points that would let a potential owner adjust some details of the resulting house.
Each building step, such as laying the foundation, framing, building walls, installing
plumbing and wiring for water and electricity, etc., can be slightly changed to make
the resulting house a little bit different from others.

DESIGN PATTERNS 28
TEMPLATE METHOD DESIGN PATTERN
Problem
Imagine that you’re creating a data mining application that analyzes corporate
documents. Users feed the app documents in various formats (PDF, DOC, CSV), and
it tries to extract meaningful data from these docs in a uniform format.
The first version of the app could work only with DOC files. In the following
version, it was able to support CSV files. A month later, you “taught” it to extract
data from PDF files.

DESIGN PATTERNS 29
TEMPLATE METHOD DESIGN PATTERN

At some point, you noticed that all three classes have a lot of similar code. While the
code for dealing with various data formats was entirely different in all classes, the
code for data processing and analysis is almost identical. Wouldn’t it be great to get
rid of the code duplication, leaving the algorithm structure intact?
DESIGN PATTERNS 30
TEMPLATE METHOD DESIGN PATTERN
Solution

The Template Method pattern suggests that you break down an algorithm into a
series of steps, turn these steps into methods, and put a series of calls to these
methods inside a single template method.
The steps may either be abstract, or have some default implementation. To use the
algorithm, the client is supposed to provide its own subclass, implement all abstract
steps, and override some of the optional ones if needed (but not the template
method itself).

DESIGN PATTERNS 31
TEMPLATE METHOD DESIGN PATTERN
Applicability

Use the Template Method pattern when you want to let clients extend only
particular steps of an algorithm, but not the whole algorithm or its structure.

Use the pattern when you have several classes that contain almost
identical algorithms with some minor differences. As a result, you might
need to modify all classes when the algorithm changes

DESIGN PATTERNS 32
TEMPLATE METHOD DESIGN PATTERN

DESIGN PATTERNS 33
MEMENTO DESIGN PATTERN
Memento is a behavioral design pattern that lets you save and restore the previous
state of an object without revealing the details of its implementation.

Assignment # 4
Read from the text book Memento design pattern, and write summary about
it , submit the report by 24-10-2024 , using the e-learning portal.

DESIGN PATTERNS 34
SUMMARY

 Behavioral design patterns are concerned with algorithms and the


assignment of responsibilities between objects.

DESIGN PATTERNS 35

You might also like