04 Design Patterns 3 Behavioral
04 Design Patterns 3 Behavioral
Programming
Behavioral Design Pattern
HELLO!
I AM HAMZEH ASEFAN
Master Degree from King Abdullah II
School of Information Technology in
Information Systems (2020/2021) /
The University of Jordan.
2
Behavioral Design
Patterns
Identifying common communication
patterns between objects and realize
these patterns.
3
1.
Chain of
Responsibility
Allows passing request along the chain of potential handlers until
one of them handles request.
“
A request from the client is
passed to a chain of objects to
process them. Later, the object
in the chain will decide
themselves who will be
processing the request and
whether the request is required
to be sent to the next object in
the chain or not.
5
Example:
6
Example:
7
Example:
8
Example:
9
Example:
10
Example:
11
2.
Iterator
Used to get a way to access the elements of a collection object in
sequential manner
“
The idea of the iterator pattern is
to take the responsibility of
accessing and passing through
the objects of the collection and
put it in the iterator object. The
iterator object will maintain the
state of the iteration, keeping
track of the current item and
having a way of identifying what
elements are next to be iterated.
13
Iterator UML Class Diagram
14
Java Enum
▪ An enum is a special "class" that represents a group of constants
Unchangeable variables.
▪ Use enums when you have values that you know aren't going to change,
like days, colors, etc.
15
Java Enum Example:
16
Iterator Example:
17
Inner Class in Java
▪ In Java, inner class refers to the class that is declared inside class:
class OuterClass {
...
class InnerClass {
...
}
}
18
Iterator Example:
19
Iterator Example:
20
Iterator VS For & For Each:
▪ For loop isn't always possible because it uses indices. Ex, Lists have
indices, but Sets don't, because they're unordered collections.
Iterator works with every kind of Iterable collection or array.
▪ You can remove elements while you're iterating, foreach loop can't.
▪ Lists also offer iterators that can iterate in both directions. A foreach
loop only iterates from the beginning to an end.
21
22
3.
Template
We can define an algorithm in a method as a series of steps.
Template
▪ Templates allows you to defines a skeleton of an algorithm
in a base class and let subclasses override the steps without
changing the overall algorithm’s structure.
24
Template Class Diagram
25
Example:
26
Example:
27
Example:
28
Example:
29
Example:
30
4.
Strategy
The strategy pattern allows us to change the behavior of an
algorithm at runtime.
Strategy
▪ Define a family of algorithms, encapsulate each one and
make them interchangeable.
33
Strategy Class Diagram
34
Example 1:
35
Example 1:
36
Example 1:
37
Example 1:
38
Example 2:
39
Example 2:
40
Example 2:
41
Example 2:
42
Example 2:
43
THANKS!
Any questions?
44