You are on page 1of 40

Software Component Design

Chapter Three

Design Pattern

4/5/2021 Software Component Design (SENG 4093) 2


Part Four
Behavioral Design Pattern

4/5/2021 Software Component Design (SENG 4093) 3


Behavioral Design Pattern
 Behavioral patterns are about identifying common
communication patterns between objects and realize these
patterns.
 Behavioral patterns describe not just patterns of objects or
classes but also the patterns of communication between
them.
 It is concerned with the inner workings of classes such as
algorithms and the responsibility between classes.
Template Method is an example of a popular and powerful
behavioral pattern.
 Behavioral patterns provide solution for the better
interaction between objects and how to provide lose coupling
and flexibility to extend easily.
Behavioral Design Pattern
 Behavioral patterns are patterns whose sole purpose is
to facilitate the work of algorithmic calculations and
communication between classes.
 Behavioral class patterns use inheritance to distribute
behavior between classes.
 Template Method: is the simpler and more common of the
two. It defines the algorithm step by step. Each step invokes
either an abstract operation or a primitive operation.
 The other behavioral class pattern is Interpreter, which
represents a grammar as a class hierarchy and implements an
interpreter as an operation on instances of these classes.
Types of Behavioural Design Pattern
 Chain of Responsibility. The chain of responsibility
pattern is used to process varied requests, each of which may
be dealt with by a different handler.
 Command. The command pattern is used to express a
request, including the call to be made and all of its required
parameters, in a command object. The command may then
be executed immediately or held for later use.
 Interpreter. The interpreter pattern is used to define the
grammar for instructions that form part of a language or
notation, whilst allowing the grammar to be easily extended.
 Iterator. The iterator pattern is used to provide a standard
interface for traversing a collection of items in an aggregate
object without the need to understand its underlying
structure.
Types of Behavioural Design Pattern
 Mediator. The mediator pattern is used to reduce coupling
between classes that communicate with each other. the
classes send messages via a mediator object.
 Memento. The memento pattern is used to capture the
current state of an object and store it in such a manner that it
can be restored at a later time without breaking the rules of
encapsulation.
 Observer. The observer pattern is used to allow an object to
publish changes to its state. Other objects subscribe to be
immediately notified of any changes.
 State. The state pattern is used to alter the behaviour of an
object as its internal state changes. The pattern allows the
class for an object to apparently change at run-time.
Types of Behavioural Design Pattern
 Strategy. The strategy pattern is used to create an
interchangeable family of algorithms from which the
required process is chosen at run-time.
 Template Method. The template method pattern is used to
define the basic steps of an algorithm and allow the
implementation of the individual steps to be changed.
 Visitor. The visitor pattern is used to separate a relatively
complex set of structured data classes from the functionality
that may be performed upon the data that they hold.
Chain of Responsibility Pattern (Behavioral)
 If you have a group of classes that are all interdependent on
each other and each performs a particular piece of
processing, this pattern is a very useful tool. It makes
sure each member in a chain controls when and to what
class it hands its processing to.
 The Chain of Responsibility pattern has a single main
component: the Handler. The handler object encapsulates
the entire chain of handler instances inside each other
instance.
 In other words, the first link in the chain contains the next
and that link contains each consecutive link.
Real Life Scenario
 For a real life scenario, in order to understand this pattern,
suppose you got a problem to solve. If you are able to handle
it on your own, you will do so, otherwise you will tell your
friend to solve it. If he’ll able to solve he will do that, or he
will also forward it to some other friend. The problem would
be forwarded until it gets solved by one of your friends or all
your friends have seen the problem, but no one is able to
solve it, in which case the problem stays unresolved.
Chain of Responsibility Pattern (Behavioral)
 Intent
 Avoid coupling the sender of a request to its
receiver by giving more than one object a chance
to handle the request.
 Chain the receiving objects and pass the request
along the chain until an object handles it.
 In other words, we can say that normally each
receiver contains reference of another receiver.
 If one object cannot handle the request then it
passes the same to the next receiver and so on.
Problem and Solution in Chain of Responsibility
 The Chain of Responsibility design pattern solves problems
like:
– How can coupling the sender of a request to its receiver be
avoided?
– How can more than one object handle a request?
• A request is an operation that one object (sender) performs
on another (receiver)
The Chain of Responsibility pattern describes how to solve
such problems:
– Chain the receiving objects and pass the request along the
chain until an object handles it.
– Define and chain Handler objects that either handle or
forward a request. This results in a chain of objects having
the responsibility to handle a request.
Advantage and Applicability
 Advantage of Chain of Responsibility Pattern
 It reduces the coupling.
 It adds flexibility while assigning the responsibilities
to objects.
 It allows a set of classes to act as one; events produced
in one class can be sent to other handler classes with
the help of composition.
 It is used:
 When more than one object can handle a request and
the handler is unknown.
 When the group of objects that can handle the request
must be specified in dynamic way.
UML CR Design Pattern
Sample Code
 Step 1: Create a Logger abstract class.
 Step 2: Create a ConsoleBasedLogger class.
 Step 3: Create a DebugBasedLogger class.
 Step 4: Create a ErrorBasedLogger class.
 Step 5: Create a ChainOfResponsibilityClient class.
Template Method Patterns (Behavioral)
 As the name suggests, it provides a template or a structure
of an algorithm which is used by users.
 A user provides its own implementation without changing
the algorithm’s structure.
 It is easier to understand this pattern with the help of a
problem.
 So, this design pattern is useful when you implement a
multistep algorithm and you want to allow customization
through subclasses.
Template Method Patterns (Behavioral)
 The Template pattern has two components: Template
class and the Concrete class.
 The template is the base or abstract class that acts as the
skeleton for all the shared functionality that gets inherited to
the class instances, or concrete classes.
 Each concrete class can override the methods and functions
of the template class or use these inherited methods without
overriding them.
Real world example
 Suppose we want to make pizza. The basic mechanism is the
same, but extra materials are added based upon the customer’s
choice whether he/she wants a vegetarian pizza or a nonvegetarian
pizza.
 For a freshman students, in general, most of the subjects in the
first semester are common for all concentrations. Later, additional
papers are added in his/her course based on his/her specialization
(Computer Science, Electronics, etc.).
Template Method Patterns (Behavioral)
 Intent
 Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses.
 The template method lets subclasses redefine certain steps of an

algorithm without changing the algorithm’s structure.


Problem and Solution in Chain of Responsibility
 The Template Method design pattern solves problems like:
– How can the invariant parts of a behavior be implemented
once so that subclasses can implement the variant parts?
– How can subclasses redefine certain parts of a behavior
(steps of an algorithm) without changing the behavior's
structure?
 It describes how to solve such problems:
– Define the skeleton of an algorithm in an operation,
deferring some steps to subclasses.
– Define a primitive operation for each variant part of a
behavior (primitive1(),primitive2(),…).
– A templateMethod() defines the skeleton (structure) of a
behavior by implementing the invariant parts and calling
primitives to defer implementing the variant parts to
Problem and Solution
 Problem: Shared functionality between classes is desired
without copying functionality

 Solution: Make both classes inherit from a single


base that contains shared functionality
Motivation
Advantage and Applicability
 Advantage of Template Pattern
 It is very common technique for reusing
the code. This is only the main benefit of
it.
 It is used:
 It is used when the common behavior among
sub-classes should be moved to a single
common class by avoiding the duplication.
UML for Template Design Pattern
Sample code
 Step 1: Create a Game abstract class.
 Step 2: Create a Chess class that will extend Game abstract
class for giving the definition to its method.
 Step 3: Create a Soccer class that will extend Game abstract
class for giving the definition to its method.
 Step 4: Create a TemplatePatternDemo class.
Interpreter Pattern (Behavioral)
 To understand this pattern, you need to be familiar with
some key terms, like sentences, grammar, languages, and so
forth.
 Terms and definitions: A language is a set of valid
sentences. A sentence = statement = expression.
 Expressions are the core components of statements. It is a
construct made up of variables, operators, and method
invocations, which are constructed according to the syntax of
the language, that evaluates to a single value.“
 A grammar is a way of formally describing the structure
(syntax) of a language. It's a list of rules, which Interpreter
uses to interpret sentences in the language. The most
common grammar notation is Extended Backus-Naur Form
(EBNF)
Cont.…
 Normally, this pattern deals with how to evaluate sentences in
a language. So, you first need to define a grammar to
represent the language. Then the interpreter deals with
that grammar.
 This pattern is best if the grammar is simple. Each class in
this pattern may represent a rule in that language, and it
should have a method to interpret an expression.
 So, to handle a greater number of rules, you need to create a
greater number of classes. This is why an interpreter pattern
should not be used to handle complex grammar.
Interpreter Pattern (Behavioral)
 Intent
 An Interpreter Pattern says that "to define a representation of
grammar of a given language, along with an interpreter that uses
this representation to interpret sentences in the language".

 Basically the Interpreter pattern has limited area where it


can be applied. We can discuss the Interpreter pattern
only in terms of formal grammars but in this area there
are better solutions that is why it is not frequently used.
 This pattern can applied for parsing the expressions
defined in simple grammars and sometimes in simple

rule engines.
Real life Example
 A language translator who translates a language for us
provides a classic example for this pattern. Or, we can
also consider music notes as our grammar and musicians as
our interpreters.
 Computer-World Example
• Java compiler interprets the Java source code into byte code
that is understandable by JVM.
• In C#, the source code is converted to MSIL code that is
interpreted by CLR. Upon execution, this MSIL(intermediate
code) is converted to native code (binary executable code) by
JIT compiler.
Advantage and Applicability
 Advantage of Interpreter Pattern
 It is easier to change and extend the grammar.
 Implementing the grammar is straightforward.
 It is used:
 When the grammar of the language is not
complicated.
 When the efficiency is not a priority.
UML for Interpreter Design Pattern
Sample Code
 Step 1: Create a Pattern interface.
 Step 2: Create a InfixToPostfixPattern class that will allow
what kind of pattern you want to convert.
 Step 3: Create a InterpreterPatternClient class that will
use InfixToPostfix Conversion.
Strategy Patterns (Behavioral)
 The Strategy Design Pattern seems to be the simplest of all
design patterns, yet it provides great flexibility to your code.
 This pattern is used almost everywhere, even in conjunction
with the other design patterns.
 The patterns we have discussed so far have a relation with
this pattern, either directly or indirectly.
 A Strategy pattern is a group of algorithms encapsulated
inside classes that are made interchangeable so the
algorithm can vary depending on the class used.
 Strategies are useful when you would like to decide at
run time when to implement each algorithm. They can
be used to vary each algorithm’s usage by its context
Real World Example
 In a football match, at the last moment, in general, if Team A
is leading Team B by a score of 1-0, instead of attacking, Team
A becomes defensive. On the other hand, Team B goes for an
all-out attack to score.
 Computer World Example
The above concept is applicable to a computer football game
also. Or, we can think of two dedicated memories where
upon fulfillment of one memory, we start storing the data in
the second available memory.
 So, a runtime check is necessary before the storing of data,
and based on the situation, we’ll proceed.
Strategy Patterns (Behavioral)
Intent
"Define a family of algorithms, encapsulate each one,
and make them interchangeable.
 Strategy lets the algorithm vary independently from
clients that use it."
 Also Known as
 The Strategy Pattern is also known as Policy.
Problem and Solution in Strategy
 The Strategy design pattern solves problems like:
 How can a class be configured with an algorithm at run-time
instead of implementing an algorithm directly?
 How can an algorithm be selected and exchanged at run-time?
 The Strategy pattern describes how to solve such problems:
 Define a family of algorithms, encapsulate each one, - define
separate classes (Strategy1,Strategy2,…) that implement
(encapsulate) each algorithm, and make them interchangeable -
and define a common interface (Strategy)through which

algorithms can be (inter)changed at run-time.


Advantage and Applicability
 Advantage of Strategy Pattern
 It provides a substitute to sub classing.
 It defines each behavior within its own class,
eliminating the need for conditional statements.
 It makes it easier to extend and incorporate new
behavior without changing the application.
 It is used:
 When the multiple classes differ only in their behaviors'.
Servlet API.
 It is used when you need different variations of an
algorithm.
UML for Strategy Pattern
Sample Code
 Step 1: Create a Strategy interface.
 Step 2: Create a Addition class that will implement Startegy
interface.
 Step 3: Create a Subtraction class that will implement
Startegy interface.
 Step 4: Create a Multiplication class that will implement
Startegy interface.
 Step 5: Create a Context class that will ask from Startegy
interface to execute the type of strategy.
 Step 6: Create a StartegyPatternDemo class.
4/5/2021 40

You might also like