0% found this document useful (0 votes)
33 views91 pages

08 - SW Design - Design Patterns - Part4

The document discusses various behavioral design patterns in software design, including the Template Method, Iterator, Strategy, and Chain of Responsibility patterns. Each pattern is explained with its definition, problems it addresses, solutions, and implementation details. The document serves as a guide for understanding how these patterns can improve code organization and maintainability.

Uploaded by

os313030
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views91 pages

08 - SW Design - Design Patterns - Part4

The document discusses various behavioral design patterns in software design, including the Template Method, Iterator, Strategy, and Chain of Responsibility patterns. Each pattern is explained with its definition, problems it addresses, solutions, and implementation details. The document serves as a guide for understanding how these patterns can improve code organization and maintainability.

Uploaded by

os313030
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Software Design Principles

08 Design Pattern– Part 4


Dr. Mostafa Elgendy
[email protected]
Agenda
§ Template Method Pattern

§ Iterator Pattern

§ Strategy Pattern

§ Chain of Responsibility

§ MVC Design Pattern

§ Summary

14-May-24 SOFTWARE DESIGN PRINCIPLES 2


Behavioral Design Patterns
§ Is a design patterns that identify common communication
patterns among objects.

§ The interaction between the objects should be in such a way


that they can easily talk to each other and still should be
loosely coupled

14-May-24 SOFTWARE DESIGN PRINCIPLES 3


Template Method Pattern

14-May-24 SOFTWARE DESIGN PRINCIPLES 4


Template Method Pattern
§ 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.

14-May-24 SOFTWARE DESIGN PRINCIPLES 5


Problem(1/2)
§ 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 extract meaningful data 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.

14-May-24 SOFTWARE DESIGN PRINCIPLES 6


Problem(2/2)
§ All three classes have a lot of similar code.
§ Code for dealing with various formats was entirely
different but the code for data processing and
analysis is identical.
§ Another problem related to client code.
§ Used lots of conditionals to pick a proper action
depending on the class of the processing object.
§ Using common interface for the three processing
classes will,
§ Eliminate the condition in client code and use
polymorphism.

14-May-24 SOFTWARE DESIGN PRINCIPLES 7


Solution(1/2)
§ You break down an algorithm into a series of steps,

§ Turn these steps into methods,

§ Put a series of calls to these methods inside a


single template method.

§ The steps may be abstract or have default


implementation.

§ To use the algorithm,


§ Client should implement all abstract steps, and override
some of the optional ones if needed (but not the template
method itself).

14-May-24 SOFTWARE DESIGN PRINCIPLES 8


Solution(2/2)
§ Let’s see the data mining app.
§ Create a base class for all three parsing algorithms.

§ This class defines a template method consisting of a


series of calls to various document-processing steps.

§ Two types of steps:


§ Abstract steps must be implemented by every
subclass

§ Optional steps already have some default


implementation, but still can be overridden if needed

14-May-24 SOFTWARE DESIGN PRINCIPLES 9


Real-World Analogy

14-May-24 SOFTWARE DESIGN PRINCIPLES 10


How to implement
§ The Abstract Class declares methods that
act as steps of an algorithm, as well as the
actual template method which calls these
methods in a specific order.
§ The steps may either be declared abstract or have
some default implementation.

§ Concrete Classes can override all of the


steps, but not the template method itself.

14-May-24 SOFTWARE DESIGN PRINCIPLES 11


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 12


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 13


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 14


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 15


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 16


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 17


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 18


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 19


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 20


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 21


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 22


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 23


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 24


Iterator Pattern

14-May-24 SOFTWARE DESIGN PRINCIPLES 25


Iterator Pattern
§ A behavioral design pattern that lets you traverse elements of a
collection without exposing its underlying representation (list,
stack, tree, etc.).

14-May-24 SOFTWARE DESIGN PRINCIPLES 26


Problem (1/2)
§ Collections are one of the most used data types in programming.
§ A container for a group of objects.

§ Most collections store their elements in simple lists.


§ Some of them are based on stacks, trees and other complex data
structures.

§ No matter how a collection is structured


§ Must provide some way of accessing its elements so, other code can use
these elements.

14-May-24 SOFTWARE DESIGN PRINCIPLES 27


Problem (2/2)
§ Easy job if you have a collection based on a list.
§ You just loop over all the elements.

§ But how to sequentially traverse elements of a complex data


structure(tree)
§ 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.

14-May-24 SOFTWARE DESIGN PRINCIPLES 28


Solution (1/2)
§ The main idea is to extract the traversal behavior of a
collection into a separate object called an iterator.

§ In addition to implementing the algorithm itself, an


iterator object encapsulates the traversal details, such as
§ The current position

§ 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.

14-May-24 SOFTWARE DESIGN PRINCIPLES 29


Solution (2/2)
§ 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 the elements.

§ All iterators must implement the same interface.


§ Makes the client code compatible with any collection type as long as
there’s a proper iterator.

§ If you need a special way to traverse a collection,


§ Just create a new iterator class, without the client.

14-May-24 SOFTWARE DESIGN PRINCIPLES 30


How to implement (1/3)
§ Iterator: interface declares the operations
required for traversing a collection:
§ Fetching the next element,

§ Retrieving the current position, etc.

§ Concrete Iterators: implement specific


algorithms for traversing a collection.
§ The iterator object should track the traversal
progress on its own.

14-May-24 SOFTWARE DESIGN PRINCIPLES 31


How to implement (2/3)
§ Collection interface: declares one or multiple
methods for getting iterators compatible with
the collection.
§ The return type of the methods must be declared as
the iterator interface so that the concrete collections
can return various kinds of iterators.

§ Concrete Collections return new instances of


a particular concrete iterator class each time
the client requests one.

14-May-24 SOFTWARE DESIGN PRINCIPLES 32


How to implement (3/3)
§ Client: works with both collections and
iterators via their interfaces.
§ This way the client isn’t coupled to concrete
classes, allowing you to use various collections
and iterators with the same client code.

§ Typically, clients don’t create iterators on


their own, but instead get them from
collections.

14-May-24 SOFTWARE DESIGN PRINCIPLES 33


When to use
§ 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).

§ To reduce duplication of the traversal code across your app.

§ When you want your code to be able to traverse different


data structures.

14-May-24 SOFTWARE DESIGN PRINCIPLES 34


Advantages
§ Single Responsibility Principle: You can clean up the
client code and the collections by extracting bulky traversal
algorithms into separate classes.

§ Open/Closed Principle: You can implement new types of


collections and iterators and pass them to existing code
without breaking anything.

14-May-24 SOFTWARE DESIGN PRINCIPLES 35


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 36


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 37


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 38


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 39


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 40


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 41


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 42


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 43


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 44


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 45


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 46


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 47


Example 4

14-May-24 SOFTWARE DESIGN PRINCIPLES 48


Example 3

14-May-24 SOFTWARE DESIGN PRINCIPLES 49


Example 4

14-May-24 SOFTWARE DESIGN PRINCIPLES 50


Example 4

14-May-24 SOFTWARE DESIGN PRINCIPLES 51


Strategy Pattern

14-May-24 SOFTWARE DESIGN PRINCIPLES 52


Strategy Pattern
§ A behavioral design pattern that lets you define a family of
algorithms, put each of them into a separate class, and make
their objects interchangeable.

14-May-24 SOFTWARE DESIGN PRINCIPLES 53


Problem (1/2)
§ You created an app for to help users navigate in any city.

§ A user enter an address and see the fastest route to that


destination the map.

§ The first version of the app could only build the routes over roads.

§ People who traveled by car were bursting with joy.

§ The next update, you added an option to build walking routes.

§ After that, you added an option to let people use public transport.

§ Later you planned to add route building for cyclists.

14-May-24 SOFTWARE DESIGN PRINCIPLES 54


Problem (2/2)
§ While the app was a success, the technical part caused you
many headaches.
§ Each time you added a new routing algorithm, the main class of the
navigator doubled in size.

§ At some point, the beast became too hard to maintain.

§ Any change to one of the algorithms affected the whole class,


increasing the chance of creating an error in already-working code.

§ Implementing a new feature requires you to change the same


huge class, conflicting with the code produced by other people.

14-May-24 SOFTWARE DESIGN PRINCIPLES 55


Solution (1/2)
§ The Strategy pattern suggests that you

§ Take a class that does something specific in a lot of different ways and extract all of
these algorithms into separate classes called strategies.

§ The original class must have a field for storing a reference to one of the
strategies.

§ It delegates the work to a linked strategy object instead of executing it on its own.

§ The client passes the desired strategy to the context.

§ It works with all strategies through the same generic interface, which only exposes a
single method for triggering the algorithm encapsulated within the selected strategy.

§ The context becomes independent of concrete strategies,

§ You can add new algorithms or modify existing ones without changing the code of the
context or other strategies.

14-May-24 SOFTWARE DESIGN PRINCIPLES 56


Solution (2/2)
§ In the navigation app,

§ Each routing algorithm can be extracted to its own class with a


single buildRoute method.

§ The method accepts an origin and destination and returns a


collection of the route’s checkpoints.

§ Even though given the same arguments, each routing


class might build a different route,

§ The main navigator class doesn’t really care which


algorithm is selected

§ Its primary job is to render a set of checkpoints on the map.

14-May-24 SOFTWARE DESIGN PRINCIPLES 57


Real-World Analogy
§ Imagine that you have to get to the
airport. You can catch a bus, order a
cab, or get on your bicycle.
§ These are your transportation
strategies.

§ You can pick one of the strategies


depending on factors such as budget
or time constraints..

14-May-24 SOFTWARE DESIGN PRINCIPLES 58


How to implement (1/2)
§ Context maintains a reference to one of the
concrete strategies and communicates with this
object only via the strategy interface.

§ The context calls the execution method on the


linked strategy object each time it needs to run the
algorithm.

§ The context doesn’t know what type of strategy it


works with or how the algorithm is executed.

14-May-24 SOFTWARE DESIGN PRINCIPLES 59


How to implement (2/2)
§ Strategy interface is common to all concrete
strategies. It declares a method the context uses
to execute a strategy.

§ Concrete Strategies implement different


variations of an algorithm the context uses.

§ Client creates a specific strategy object and


passes it to the context. The context exposes a
setter which lets clients replace the strategy
associated with the context at runtime.

14-May-24 SOFTWARE DESIGN PRINCIPLES 60


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 61


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 62


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 63


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 64


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 65


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 66


Example 2

14-May-24 SOFTWARE DESIGN PRINCIPLES 67


Chain of Responsibility

14-May-24 SOFTWARE DESIGN PRINCIPLES 68


Chain of Responsibility
§ 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.

14-May-24 SOFTWARE DESIGN PRINCIPLES 69


Problem (1/3)
§ You’re working on an online ordering system.

§ You want to restrict access to the system so only authenticated


users can create orders.

§ Users who have administrative permissions must have full access


to all orders.

§ You realized that these checks must be performed


sequentially.

§ The application can attempt to authenticate a user to the system.

§ However, if those credentials aren’t correct and authentication fails,


there’s no reason to proceed with any other checks.

14-May-24 SOFTWARE DESIGN PRINCIPLES 70


Problem (2/3)
§ During the next few months, you implemented more of
those sequential checks.
§ One of your colleagues suggested that it’s unsafe to pass raw
data straight to the ordering system. So you added an extra
validation step to sanitize the data in a request.

§ Later, somebody noticed that the system is vulnerable to brute


force password cracking. To negate this, you promptly added a
check that filters repeated failed requests coming from the
same IP address.

§ Someone else suggested that you could speed up the system


by returning cached results on repeated requests containing the
same data.

14-May-24 SOFTWARE DESIGN PRINCIPLES 71


Problem (3/3)
§ The code of the checks, which had already looked like a
mess, became more and more bloated as you added
each new feature.

§ Changing one check sometimes affected the others.

§ Worst of all, when you tried to reuse the checks to


protect other components of the system,

§ you had to duplicate some of the code since those components


required some of the checks, but not all of them.

§ The system became very hard to comprehend and


expensive to maintain.

14-May-24 SOFTWARE DESIGN PRINCIPLES 72


Solution (1/2)
§ Chain of Responsibility relies on transforming 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 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.

§ A handler can decide not to pass the request further down the chain and stop any further processing.

§ 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.

14-May-24 SOFTWARE DESIGN PRINCIPLES 73


Solution (2/2)
§ There’s a different approach in which, upon receiving a request,

§ A handler decides whether it can process it. If it can, it doesn’t pass the request
any further.

§ So it’s either only one handler that processes the request or none at all.

§ This is very common when dealing with events in stacks of elements


within a GUI.

§ When a user clicks a button, the event propagates through the chain of GUI
elements that starts with the button, goes along its containers (like forms or
panels), and ends up with the main application window.

§ The event is processed by the first element in the chain that’s capable of
handling it. This example shows that a chain can always be extracted from an
object tree.

14-May-24 SOFTWARE DESIGN PRINCIPLES 74


How to implement (1/2)
§ Handler declares the interface, common for all concrete
handlers. It usually contains just a single method for handling
requests, but sometimes it may also have another method for
setting the next handler on the chain.

§ The Base Handler is an optional class where you can put the
boilerplate code that’s common to all handler classes.

§ Usually, this class defines a field for storing a reference to the


next handler. The clients can build a chain by passing a
handler to the constructor or setter of the previous handler.
The class may also implement the default handling behavior:
it can pass execution to the next handler after checking for its
existence.

14-May-24 SOFTWARE DESIGN PRINCIPLES 75


How to implement (2/2)
§ Concrete Handlers contain the actual code for processing
requests. Upon receiving a request, each handler must decide
whether to process it and, additionally, whether to pass it
along the chain.

§ Handlers are usually self-contained and immutable, accepting


all necessary data just once via the constructor.

§ The Client may compose chains just once or compose them


dynamically, depending on the application’s logic. Note that a
request can be sent to any handler in the chain—it doesn’t
have to be the first one.

14-May-24 SOFTWARE DESIGN PRINCIPLES 76


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 77


MVC

14-May-24 SOFTWARE DESIGN PRINCIPLES 78


MVC Design Pattern
§ The MVC design pattern is a software
architecture pattern that separates an
application into three main components:
§ Model, View, and Controller, making it easier to
manage and maintain the codebase.

§ It also allows for the reusability of


components and promotes a more modular
approach to software development.

14-May-24 SOFTWARE DESIGN PRINCIPLES 79


Components of the MVC Design Pattern
§ Model:

§ The Model component represents the


data and business logic of an application.

§ It is responsible for managing the


application’s data, processing business
rules, and responding to requests for
information from other components, such
as the View and the Controller

14-May-24 SOFTWARE DESIGN PRINCIPLES 80


Components of the MVC Design Pattern
§ View:
§ Displays the data from the Model to the
user and sends user inputs to the
Controller.

§ It is passive and does not directly interact


with the Model.

§ Instead, it receives data from the Model


and sends user inputs to the Controller
for processing.

14-May-24 SOFTWARE DESIGN PRINCIPLES 81


Components of the MVC Design Pattern
§ Controller:

§ Acts as an intermediary between the


Model and the View.

§ It handles user input and updates the


Model accordingly and updates the View
to reflect changes in the Model.

§ It contains application logic, such as


input validation and data transformation

14-May-24 SOFTWARE DESIGN PRINCIPLES 82


Components of the MVC Design Pattern
§ Controller:

§ Acts as an intermediary between the


Model and the View.

§ It handles user input and updates the


Model accordingly and updates the View
to reflect changes in the Model.

§ It contains application logic, such as


input validation and data transformation

14-May-24 SOFTWARE DESIGN PRINCIPLES 83


Communication between the components
§ User Interaction with View:
§ The user interacts with the View, such as clicking a button or entering text into a form.

§ View Receives User Input:


§ The View receives the user input and forwards it to the Controller.

§ Controller Processes User Input:


§ The Controller receives the user input from the View.

§ It interprets the input, performs any necessary operations (such as updating the
Model), and decides how to respond.

14-May-24 SOFTWARE DESIGN PRINCIPLES 84


Communication between the components
§ Controller Updates Model:

§ The Controller updates the Model based on the user input or application
logic.

§ Model Notifies View of Changes:

§ If the Model changes, it notifies the View.

§ View Requests Data from Model:

§ The View requests data from the Model to update its display.

14-May-24 SOFTWARE DESIGN PRINCIPLES 85


Communication between the components
§ Controller Updates View:

§ The Controller updates the View based on the changes in the Model
or in response to user input.

§ View Renders Updated UI:

§ The View renders the updated UI based on the changes made by


the Controller.

14-May-24 SOFTWARE DESIGN PRINCIPLES 86


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 87


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 88


Example 1

14-May-24 SOFTWARE DESIGN PRINCIPLES 89


Summary
§ Template Method Pattern

§ Iterator Pattern

§ Strategy Pattern

§ Chain of Responsibility

§ MVC Design Pattern

14-May-24 MOBILE PROGRAMMING 90


Questions

14-May-24 MOBILE PROGRAMMING 91

You might also like