Chapter 2

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 91

DAMBI DOLLO UNIVERSITY

Department of Software Engineering


Software Architecture and Design

By Moti T.
October 12, 2023
KIOT@SE by Ashenafi Workie
Chapter 2: Design Patterns
1 What are design patterns
2 Creational design patterns
3 Structural design patterns
4 Behavioral design patterns
Design pattern
Design patterns are solutions to general software development problems.
design patterns are programming language independent strategies for solving
the common object-oriented design problems. That means, a design pattern
represents an idea, not a particular implementation.
Design patterns capture the best practices of experienced object-oriented
software developers.
“Each pattern describes a problem which occurs over and over again in our
environment, and then describes the core of the solution to that problem, in such a
way that you can use this solution a million times over, without ever doing it the
same way twice.” [1] [Christopher Alexander] 3
Pattern Elements
In general, a pattern has the following essential elements.
The pattern name
The problem
The solution
The pattern name is a handle we can use to describe a design problem, its
solutions, and consequences in a word or two.
Naming a pattern immediately increases the design vocabulary.
It lets us design at a higher level of abstraction.
It makes it easier to think about designs and to communicate them and their
tradeoffs to others. 4
Problems
The problem describes when to apply the pattern.
It explains the problem and its context.
It might describe specific design problems such as how to represent
algorithms as objects.
It might describe class or object structures that are symptomatic of an
inflexible design.
Sometimes the problem will include a list of conditions that must be met
before it makes sense to apply the pattern..

5
solution
The solution describes the elements that make up the design, their
relationships, responsibilities and collaborations.
The solution doesn't describe a particular concrete design or implementation,
because a pattern is like a template that can be applied in many different
situations.
Instead, the pattern provides an abstract description of a design problem and
how a general arrangement of elements (classes and objects in our case)
solves it.

6
Advantages of design pattern
They are reusable in multiple projects.
They provide the solutions that help to define the system architecture.
They capture the software engineering experiences.
They provide transparency to the design of an application.
They are well-proved and testified solutions since they have been built
upon the knowledge and experience of expert software developers.
Design patterns don't guarantee an absolute solution to a problem.
They provide clarity to the system architecture and the possibility of
building a better system.

7
Types of Design Patterns
Design patterns are divided into three types:
Creational patterns are ones that create objects for you, rather than having
you instantiate objects directly. This gives your program more flexibility in
deciding which objects need to be created for a given case.
Structural patterns help you compose groups of objects into larger structures,
such as complex user interfaces or accounting data.
Behavioral patterns help you define the communication between objects in
your system and how the flow is controlled in a complex program.

8
Types Design pattern
Creational patterns Behavioral patterns
Structural patterns
1.Factory Pattern 1.Adapter Pattern 1.Chain Of Responsibility
2.Command Pattern
2.Abstract Factory Pattern 2.Bridge Pattern 3.Interpreter Pattern
3.Singleton Pattern 3.Composite Pattern 4.Iterator Pattern
5.Mediator Pattern
4.Prototype Pattern 4.Decorator Pattern 6.Memento Pattern
5.Builder Pattern 5.Facade Pattern 7.Observer Pattern
8.State Pattern
6.Flyweight Pattern 9.Strategy Pattern
7.Proxy Pattern 10.Template Pattern
11.Visitor Pattern

9
Creational Design
pattern
The creational patterns deal with the best way to create instances of objects.
These design patterns are all about class instantiation or object creation.
It is ones that create objects for you, rather than having you instantiate objects directly.
This gives your program more flexibility in deciding which objects need to be created for a
given case.
These patterns can be further categorized into Class-creational patterns and object-
creational patterns.
While class-creation patterns use inheritance effectively in the instantiation process, object-
creation patterns use delegation effectively to get the job done.
Student = new Student(); //instance of Student class
This amounts to hard coding, depending on how you create the object within your program.
10
1.Creational

Compiled by Ashenafi W. (MSc.) 11


1.Creational /Factory Pattern
The Factory Pattern provides a simple decision making class that returns one
of several possible subclasses of an abstract base class depending on the data
that are provided.
A Factory Pattern or Factory Method Pattern says that just define an interface
or abstract class for creating an object but let the subclasses decide
which class to instantiate.

12
1.Creational /Factory Pattern
Advantage of Factory Design Pattern
Factory Method Pattern allows the sub-classes to choose the type of
objects to create.
It promotes the loose-coupling by eliminating the need to bind
application-specific classes into the code. That means the code
interacts solely with the resultant interface or abstract class, so that
it will work with any classes that implement that interface or that
extends that abstract class.

13
1.Creational /Factory Pattern
Usage of Factory Design Pattern
When a class doesn't know what sub-classes will be required to
create
When a class wants that its sub-classes specify the objects to be
created.
When the parent classes choose the creation of objects to its sub-
classes.

14
1.Creational /Factory Pattern
E.g.GenerateBill class will use GetPlanFactory to get a Plan object. It will pass
information (DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN)
to GetPalnFactory to get the type of object it needs.

Compiled by Ashenafi W. (MSc.) 15


1.Creational /Factory Pattern
Plan.java CommercialPlan.java
import java.io.*; class CommercialPlan extends Plan{
abstract class Plan{ //@override
protected double rate; public void getRate(){
abstract void getRate(); rate=7.50;
}
public void calculateBill(int units){ InstitutionalPlan.java
System.out.println(units*rate);
} class InstitutionalPlan extends Plan{
}//end of Plan class. //@override
DomesticPlan.java public void getRate(){
class DomesticPlan extends Plan{ rate=5.50;
//@override }
public void getRate(){
rate=3.50;
}
}//end of DomesticPlan class.

16
1.Creational /Factory Pattern class GenerateBill{
GetPlanFactory.java
public static void main(String args[])throws IOException{
class GetPlanFactory{
GetPlanFactory planFactory = new GetPlanFactory();
//use getPlan method to get object of type Plan
System.out.print("Enter the name of plan for which the bill will
public Plan getPlan(String planType){
be generated: ");
if(planType == null){
BufferedReader br=new BufferedReader(new InputStreamRea
return null;
der(System.in));
}
if(planType.equalsIgnoreCase("DOMESTICPLAN")) {
String planName=br.readLine();
return new DomesticPlan();
System.out.print("Enter the number of units for bill will be calc
}
ulated: ");
else if(planType.equalsIgnoreCase("COMMERCIALPLAN"))
int units=Integer.parseInt(br.readLine());
{
return new CommercialPlan();
Plan p = planFactory.getPlan(planName);
}
//
else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN"))
call getRate() method and calculateBill()method of DomesticPaln.
{
return new InstitutionalPlan();
System.out.print("Bill amount for "+planName+" of "+units+
}
" units is: ");
return null;
p.getRate();
}
p.calculateBill(units);
}//end of GetPlanFactory class.
}
}//end of GenerateBill class

17
1.Creational /Factory Pattern
FactoryPatternDemo, our demo class, will use ShapeFactory to get a Shape
object.It will pass information (CIRCLE / RECTANGLE / SQUARE) to
ShapeFactory to get the type of object it needs.

18
1.Creational /Factory Pattern
Shape.java Square.java
public interface Shape { public class Square implements Shape {
void draw(); @Override
} public void draw() {
Rectangle.java System.out.println("Inside Square::draw()
public class Rectangle implements Shape { method.");
@Override } }
public void draw() { Circle.java

System.out.println("Inside Rectangle::draw() public class Circle implements Shape {

method."); @Override

} public void draw() {

} System.out.println("Inside Circle::draw()
method.");
}}
19
1.Creational /Factory Pattern
ShapeFactory.java public class FactoryPatternDemo {

public class ShapeFactory { public static void main(String[] args) {


ShapeFactory shapeFactory = new ShapeFactory();
//use getShape method to get object of type shape
//get an object of Circle and call its draw method.
public Shape getShape(String shapeType){
Shape shape1 = shapeFactory.getShape("CIRCLE");
if(shapeType == null){ //call draw method of Circle
return null; shape1.draw();
} //get an object of Rectangle and call its draw method.

if(shapeType.equalsIgnoreCase("CIRCLE")){ Shape shape2 = shapeFactory.getShape("RECTANGLE");

return new Circle(); //call draw method of Rectangle


shape2.draw();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
//get an object of Square and call its draw method.
return new Rectangle();
Shape shape3 = shapeFactory.getShape("SQUARE");
} else if(shapeType.equalsIgnoreCase("SQUARE")){ //call draw method of circle
return new Square();
shape3.draw();
}
} }
return null;

}}
20
2.Creational / Abstract Factory Pattern
The Abstract Factory Pattern provides an interface to create and return one
of several families of related objects.
Abstract Factory Pattern says that just define an interface or abstract class
for creating families of related (or dependent) objects but without
specifying their concrete sub-classes.
Advantage of Abstract Factory Pattern
Abstract Factory Pattern isolates the client code from concrete
(implementation) classes.
It eases the exchanging of object families.
It promotes consistency among objects.
21
2.Creational / Abstract Factory Pattern
Usage of Abstract Factory Pattern
When the system needs to be independent of how its object are created,
composed, and represented.
When the family of related objects has to be used together, then this constraint
needs to be enforced.
When you want to provide a library of objects that does not show
implementations and only reveals interfaces.
When the system needs to be configured with one of a multiple family of
objects.

22
2.Creational / Abstract Factory Pattern

23
1.Creational / Abstract Factory Pattern
Bank .java SBI .java
import java.io.*; class SBI implements Bank{
private final String BNAME;
interface Bank{
public SBI(){
String getBankName(); BNAME="SBI BANK";
} }
public String getBankName(){
HDFC.java return BNAME;
class HDFC implements Bank{ }
}
private final String BNAME;
Loan.java
public HDFC(){ abstract class Loan{
BNAME="HDFC BANK"; protected double rate;
} abstract void getInterestRate(double rate);
public String getBankName() { public void calculateLoanPayment(double loanamount, int years)
return BNAME; {
double EMI;
}
int n;
}
ICICI.java n=years*12;
class ICICI implements Bank{ rate=rate/1200;
private final String BNAME; EMI=((rate*Math.pow((1+rate),n))/((Math.pow((1+rate),n))-
ICICI(){ 1))*loanamount;
BNAME="ICICI BANK";
System.out.println("your monthly EMI is "+ EMI +" for the amount"+loana
} mount+" you have borrowed");
public String getBankName() { }
return BNAME; }//
} }
24
1.Creational /Abstract Factory Pattern
HomeLoan.java AbstractFactory.java
class HomeLoan extends Loan{ abstract class AbstractFactory{
public void getInterestRate(double r){ public abstract Bank getBank(String bank);
rate=r; public abstract Loan getLoan(String loan);
} }
}//End of the HomeLoan class. AbstractFactory.java
BussinessLoan.java
class BussinessLoan extends Loan{ class BankFactory extends AbstractFactory{
public void getInterestRate(double r){ public Bank getBank(String bank){
if(bank == null){
rate=r; return null;
} }
if(bank.equalsIgnoreCase("HDFC")){
EducationLoan.java return new HDFC();
class EducationLoan extends Loan{ } else if(bank.equalsIgnoreCase("ICICI")){
public void getInterestRate(double r){ return new ICICI();
rate=r; } else if(bank.equalsIgnoreCase("SBI")){
} return new SBI();
}
return null;
}
public Loan getLoan(String loan) {
return null;
}
}//End of the BankFactory class. 25
1.Creational /Abstract Factory Pattern
class FactoryCreator {
LoanFactory.java public static AbstractFactory getFactory(String choice){
class LoanFactory extends AbstractFactory{ if(choice.equalsIgnoreCase("Bank")){
public Bank getBank(String bank){ return new BankFactory();
return null; } else if(choice.equalsIgnoreCase("Loan")){
} return new LoanFactory();
}
public Loan getLoan(String loan){ return null;
if(loan == null){ }
return null; }//End of the FactoryCreator.
}
if(loan.equalsIgnoreCase("Home")){
return new HomeLoan();
} else if(loan.equalsIgnoreCase("Business")){
return new BussinessLoan();
} else if(loan.equalsIgnoreCase("Education")){
return new EducationLoan();
}
return null;
}

26
1.Creational /Abstract Factory Pattern
LoanFactory.java double rate=Double.parseDouble(br.readLine());
import java.io.*; System.out.print("\n");
class AbstractFactoryPatternExample { System.out.print("Enter the loan amount you want to take: ");
public static void main(String args[])throws IOException {
double loanAmount=Double.parseDouble(br.readLine());
System.out.print("\n");
BufferedReader br=new BufferedReader(new InputStreamRe System.out.print("Enter the number of years to pay your entire lo
ader(System.in)); an amount: ");
int years=Integer.parseInt(br.readLine());
System.out.print("Enter the name of Bank from where you wa
nt to take loan amount: "); System.out.print("\n");
String bankName=br.readLine(); System.out.println("you are taking the loan from "+ b.getBankNa
me());
System.out.print("\n");
System.out.print("Enter the type of loan e.g. home loan or busine AbstractFactory loanFactory = FactoryCreator.getFactory("Loan");
ss loan or education loan : ");
Loan l=loanFactory.getLoan(loanName);
String loanName=br.readLine(); l.getInterestRate(rate);
AbstractFactory bankFactory = FactoryCreator.getFactory("Bank"); l.calculateLoanPayment(loanAmount,years);
}
Bank b=bankFactory.getBank(bankName); }//End of the AbstractFactoryPatternExample

System.out.print("\n");

27
3.Creational / Singleton Pattern
The Singleton Pattern is a class of which there can be no more than one instance.
It provides a single global point of access to that instance.
Intent
Ensure a class has only one instance, and provide a global point of access to it.
Encapsulated "just-in-time initialization" or "initialization on first use".
Problem
Application needs one, and only one, instance of an object. Additionally, lazy initialization
and global access are necessary.

28
3.Creational / Singleton Pattern

How to create Singleton design pattern?


To create the singleton class, we need to have static member of class,
private constructor and static factory method.
Static member: It gets memory only once because of static, it
contains the instance of the Singleton class.
Private constructor: It will prevent to instantiate the Singleton class
from outside the class.
Static factory method: This provides the global point of access to the
Singleton object and returns the instance to the caller.
29
3.Creational / Early Instantiation of Singleton Pattern
Early instantiation
File: A.java File: A.java
class A{
class A{
private static A obj=new A();//
private static A obj=new A(); Early, instance will be created at load time
// private A(){}
Early, instance will be created at load time
public static A getA(){
return obj;
private A(){} }

public static A getA(){ public void doSomething(){


//write your code
return obj; }
} }

public void doSomething(){


//write your code
}
}
30
Cont’d
Singleton should be considered only if all three of the following criteria are satisfied:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
Early Instantiation: creation of instance at load time.
Lazy Instantiation: creation of instance when required.
Advantage of Singleton design pattern
Saves memory because object is not created at each request.
Only single instance is reused again and again.

31
3.Creational / lazy Instantiation of Singleton Pattern

Compiled by Ashenafi W. (MSc.) 32


3.Creational / lazy Instantiation of Singleton Pattern
Lazy instantiation singlton more1
File: A.java
class A{
private static A obj;
private A(){}
singleton more2
public static A getA(){
if (obj == null){
synchronized(Singleton.class){
if (obj == null){
obj = new Singleton();//
instance will be created at request time
}
}
}
return obj;
}

public void doSomething(){


//write your code
}
}

33
4.Creational / Prototype Pattern
Prototype Pattern says that cloning of an existing object instead
of creating new one and can also be customized as per the
requirement.
Advantage of Prototype Pattern
It reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing which type of object
it will be.
It lets you add or remove objects at runtime.
34
4.Creational / Prototype Pattern
Usage of Prototype Pattern
When the classes are instantiated at runtime.
When the cost of creating an object is expensive or complicated.
When you want to keep the number of classes in an application
minimum.
When the client application needs to be unaware of object creation
and representation.

35
4.Creational / Prototype Pattern

Compiled by Ashenafi W. (MSc.) 36


5.Creational / Builder Pattern
Builder Pattern says that "construct a complex object from
simple objects using step-by-step approach“
Advantage of Builder Design Pattern
It provides clear separation between the construction and
representation of an object.
It provides better control over construction process.
It supports to change the internal representation of objects

37
5.Creational / Builder Pattern

Compiled by Ashenafi W. (MSc.) 38


6.Creational / Object Pool Pattern
Object Pool Pattern says that " to reuse the object that are expensive to
create".
Advantage of Object Pool design pattern
It boosts the performance of the application significantly.
It is most effective in a situation where the rate of initializing a class instance is
high.
It manages the connections and provides a way to reuse and share them.
It can also provide the limit for the maximum number of objects that can be
created.

39
6.Creational / Object Pool Pattern
Object Pool Pattern says that " to reuse the object that are expensive to
create".
Advantage of Object Pool design pattern
It boosts the performance of the application significantly.
It is most effective in a situation where the rate of initializing a class instance is
high.
It manages the connections and provides a way to reuse and share them.
It can also provide the limit for the maximum number of objects that can be
created.

40
6.Creational / Object Pool Pattern
When an application requires objects which are expensive to create.
Eg: there is a need of opening too many connections for the
database then it takes too longer to create a new one and the
database server will be overloaded.
When there are several clients who need the same resource at
different times.

41
6.Creational / Object Pool Pattern

Compiled by Ashenafi W. (MSc.) 42


Structural Design pattern
Structural design patterns are concerned with how classes and objects can be
composed, to form larger structures.
The structural design patterns simplifies the structure by identifying the
relationships.
These patterns focus on, how the classes inherit from each other and how they are
composed from other classes.

43
Structural design patterns

44
Structural design patterns
There are following 7 types of structural design patterns.
Adapter Pattern: Adapting an interface into another according to client
expectation.
Bridge Pattern: Separating abstraction (interface) from implementation.
Composite Pattern: Allowing clients to operate on hierarchy of objects.
Decorator Pattern: Adding functionality to an object dynamically.
Facade Pattern Providing an interface to a set of interfaces.
Flyweight Pattern: Reusing an object by sharing it.
Proxy Pattern: Representing another object.

45
1.Structural / Adapter Pattern
An Adapter Pattern says that just "converts the interface of a class into another
interface that a client wants“
Advantage of Adapter Pattern
It allows two or more previously incompatible objects to interact.
It allows reusability of existing functionality.
Usage of Adapter pattern:
When an object needs to utilize an existing class with an incompatible interface.
When you want to create a reusable class that cooperates with classes which don't
have compatible interfaces.
When you want to create a reusable class that cooperates with classes which don't
have compatible interfaces. 46
Structural / Adapter Pattern

Compiled by Ashenafi W. (MSc.) 47


2.Structural / Bridge Pattern
Bridge Pattern: Separating abstraction (interface) from implementation.
A Bridge Pattern says that just "decouple the functional abstraction from the
implementation so that the two can vary independently".
Advantage of Bridge Pattern
It enables the separation of implementation from the interface.
It improves the extensibility.
It allows the hiding of implementation details from the client.
Usage of Bridge Pattern
If don't want a permanent binding between the functional abstraction and its implementation.
When both the functional abstraction and implementation need to extended using sub-classes.
It is mostly used in those places where changes are made in the implementation does not affect
the clients. 48
Structural / Bridge Pattern

49
3.Structural / Composite Pattern
Composite Pattern: Allowing clients to operate on hierarchy of objects.
A Composite Pattern says that just "allow clients to operate in generic manner on
objects that may or may not represent a hierarchy of objects".
Advantage of Composite Design Pattern
It defines class hierarchies that contain primitive and complex objects.
It makes easier to you to add new kinds of components.
It provides flexibility of structure with manageable class or interface.
Usage of Composite Pattern
When you want to represent a full or partial hierarchy of objects.
When the responsibilities are needed to be added dynamically to the individual objects
without affecting other objects. Where the responsibility of object may vary from time to
50
time.
Structural / Composite Pattern

51
Structural / Composite Pattern

52
4.Structural / Decorator Pattern
Decorator Pattern: Adding functionality to an object dynamically.
A Decorator Pattern says that just "attach a flexible additional
responsibilities to an object dynamically".
Advantage of Decorator Pattern
It provides greater flexibility than static inheritance.
It enhances the extensibility of the object, because changes are made by
coding new classes.
It simplifies the coding by allowing you to develop a series of
functionality from targeted classes instead of coding all of the behavior
into the object.
53
4.Structural / Decorator Pattern
Usage of Decorator Pattern
It is used:
When you want to transparently and dynamically add responsibilities to
objects without affecting other objects.
When you want to add responsibilities to an object that you may want to
change in future.
Extending functionality by sub-classing is no longer practical.

54
4.Structural / Decorator Pattern

Compiled by Ashenafi W. (MSc.) 55


5. Structural / Facade Pattern
A Facade Pattern says that just "just provide a unified and simplified interface to a
set of interfaces in a subsystem, therefore it hides the complexities of the
subsystem from the client".
Advantage of Facade Pattern
It shields the clients from the complexities of the sub-system components.
It promotes loose coupling between subsystems and its clients
Usage of Facade Pattern:
When you want to provide simple interface to a complex sub-system.
When several dependencies exist between clients and the implementation classes of
an abstraction.
56
Structural / Facade Pattern

57
6. Structural / Flyweight Pattern
Flyweight Pattern: Reusing an object by sharing it.
A Flyweight Pattern says that just "to reuse already existing similar kind of objects by
storing them and create new object when no matching object is found".
Advantage of Flyweight Pattern
It reduces the number of objects.
It reduces the amount of memory and storage devices required if the objects are persisted
Usage of Flyweight Pattern
When an application uses number of objects
When the storage cost is high because of the quantity of objects.
When the application does not depend on object identity.

58
Structural / Flyweight Pattern

Compiled by Ashenafi W. (MSc.) 59


7. Structural / Proxy Pattern
Proxy Pattern: Representing another object.
Simply, proxy means an object representing another object.
According to GoF, a Proxy Pattern "provides the control for accessing
the original object".
RMI API uses proxy design pattern. Stub and Skeleton are two proxy objects used
in RMI.
Advantage of Proxy Pattern
It provides the protection to the original object from the outside world.

Compiled by Ashenafi W. (MSc.) 60


Structural / Proxy Pattern
Usage of Proxy Pattern:
It can be used in Virtual Proxy scenario---Consider a situation where there is multiple
database call to extract huge size image. This avoids duplication of the object and hence
saving memory.
It can be used in Protective Proxy scenario---It acts as an authorization layer to verify that
whether the actual user has access the appropriate content or not. Only the websites and
contents which are valid will be allowed and the remaining ones will be blocked.
It can be used in Remote Proxy scenario---A remote proxy can be thought about the stub
in the RPC call. Another example can be providing interface for remote resources such as
web service or REST resources.
It can be used in Smart Proxy scenario---A smart proxy provides additional layer of security
by interposing specific actions when the object is accessed. 61
Structural / Proxy Pattern

62
Behavioral design patterns

There are 12 types of structural design patterns: 8.State Pattern


1.Chain of Responsibility Pattern 9.Strategy Pattern
2.Command Pattern 10.Template Pattern
3.Interpreter Pattern 11.Visitor Pattern
4.Iterator Pattern 12.Null Object
5.Mediator Pattern
6.Memento Pattern
7.Observer Pattern

Compiled by Ashenafi W. (MSc.) 63


1.Behavioral /Chain of Responsibility Pattern
A Chain of Responsibility Pattern says that just "avoid coupling the sender of a request to
its receiver by giving multiple objects a chance to handle the request".
For example, an ATM uses the Chain of Responsibility design pattern in money giving
process.
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.
Usage of Chain of Responsibility Pattern:
When more than one object can handle a request and the handler is unknown.
64
1.Behavioral /Chain of Responsibility Pattern

65
2.Behavioral /Command Pattern
A Command Pattern says that "encapsulate a request under an object as a command
and pass it to invoker object.
Invoker object looks for the appropriate object which can handle this command and
pass the command to the corresponding object and that object executes the
command".
It is also known as Action or Transaction.
Advantage of command pattern
It separates the object that invokes the operation from the object that actually
performs the operation.
It makes easy to add new commands, because existing classes remain unchanged.
66
67
2.Behavioral /Command Pattern
Usage of command pattern:
When you need parameterize objects according to an action perform.
When you need to create and execute requests at different times.
When you need to support rollback, logging or transaction functionality.
see the example

68
2.Behavioral /Command Pattern

69
3.Behavioral /Interpreter Pattern
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".

Advantage of Interpreter Pattern


It is easier to change and extend the grammar.
Implementing the grammar is straightforward.
Usage of Interpreter pattern:
When the grammar of the language is not complicated.
When the efficiency is not a priority

70
3.Behavioral /Interpreter Pattern

Compiled by Ashenafi W. (MSc.) 71


4.Behavioral /Iterator Pattern
Iterator Pattern is used "to access the elements of an aggregate object
sequentially without exposing its underlying implementation“
Advantage of Iterator Pattern
It supports variations in the traversal of a collection.
It simplifies the interface to the collection.
Usage of Iterator Pattern:
When you want to access a collection of objects without exposing its
internal representation.
When there are multiple traversals of objects need to be supported in
the collection. 72
4.Behavioral /Iterator Pattern

Compiled by Ashenafi W. (MSc.) 73


5.Behavioral /Mediator Pattern
A Mediator Pattern says that "to define an object that encapsulates how a set of objects interact".
Mediator pattern is used to reduce communication complexity between multiple objects or classes.
This pattern provides a mediator class which normally handles all the communications between
different classes and supports easy maintainability of the code by loose coupling.
Benefits:
It decouples the number of classes.
It simplifies object protocols.
It centralizes the control.
The individual components become simpler and much easier to deal with because they don't need
to pass messages to one another
The components don't need to contain logic to deal with their intercommunication and therefore,
they are more generic 74
5.Behavioral /Mediator Pattern
Usage:
It is commonly used in message-based systems likewise chat applications.
When the set of objects communicate in complex but in well-defined ways.

75
5.Behavioral /Mediator Pattern

76
6.Behavioral /Memento Pattern

A Memento Pattern says that "to restore the state of an object to its previous state".
But it must do this without violating Encapsulation. Such case is useful in case of
error or failure.
The Memento pattern is also known as Token.
Undo or backspace or ctrl+z is one of the most used operation in an editor.
Memento design pattern is used to implement the undo operation. This is done by
saving the current state of the object as it changes state.

77
6.Behavioral /Memento Pattern

Benefits:
It preserves encapsulation boundaries.
It simplifies the originator.
Usage:
It is used in Undo and Redo operations in most software.
It is also used in database transactions.

78
6.Behavioral /Memento Pattern

79
7.Behavioral /Observer Pattern
An Observer Pattern says that "just define a one-to-one dependency so that when one object
changes state, all its dependents are notified and updated automatically".
The Memento pattern is also known as Dependents or Publish-Subscribe.
Benefits:
It describes the coupling between the objects and the observer.
It provides the support for broadcast-type communication.
Usage:
When the change of a state in one object must be reflected in another object without keeping the
objects tight coupled.
When the framework we writes and needs to be enhanced in future with new observers with
minimal chamges.

80
7.Behavioral /Observer Pattern

81
8.Behavioral /State Pattern
A State Pattern says that "the class behavior changes based on its state".
In State Pattern, we create objects which represent various states and a context object
whose behavior varies as its state object changes.
The State Pattern is also known as Objects for States.
Benefits:
It keeps the state-specific behavior.
It makes any state transitions explicit.
Usage:
When the behavior of object depends on its state and it must be able to change its
behavior at runtime according to the new state.
It is used when the operations have large, multipart conditional statements that depend
on the state of an object. 82
8.Behavioral /State Pattern

83
9.Behavioral / Strategy Pattern
A Strategy Pattern says that "defines a family of functionality, encapsulate each one,
and make them interchangeable".
The Strategy Pattern is also known as Policy.
Benefits:
It provides a substitute to subclassing.
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.
Usage:
When the multiple classes differ only in their behaviors.e.g. Servlet API.
84
It is used when you need different variations of an algorithm.
9.Behavioral / Strategy Pattern

85
10.Behavioral / Template Pattern

A Template Pattern says that "just define the skeleton of a function in


an operation, deferring some steps to its subclasses“.
Benefits:
It is very common technique for reusing the code.This is only the
main benefit of it.
Usage:
It is used when the common behavior among sub-classes should be
moved to a single common class by avoiding the duplication.

86
10.Behavioral / Template Pattern

87
11.Behavioral / Visitor Pattern
Represent an operation to be performed on the elements of an object structure. Visitor
lets you define a new operation without changing the classes of the elements on which it
operates.
The Visitor pattern makes adding new operations (or utilities) easy - simply add a new
Visitor derived class.
But, if the subclasses in the aggregate node hierarchy are not stable, keeping the Visitor
subclasses in sync requires a prohibitive amount of effort.

88
11.Behavioral / Visitor Pattern

89
11.Behavioral / Visitor Pattern

90
End ….

Thank you

91

You might also like