0% found this document useful (0 votes)
2 views107 pages

Design Patterns

Uploaded by

raghadshaar20
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)
2 views107 pages

Design Patterns

Uploaded by

raghadshaar20
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

Dr.

Amjad AbuHassan

2/21/24 Dr. Amjad AbuHassan 1


Design Patterns in Architecture
● A pattern is a recurring solution to a standard problem, in a
context.
● Christopher Alexander, professor of architecture...
● A pattern describes a problem that occurs repeatedly 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.”

2/21/24 Dr. Amjad AbuHassan 2


Patterns in Engineering
● How do other engineers find and use patterns?
● Mature engineering disciplines have handbooks describing successful solutions to known
problems

● Automobile designers don't design cars from scratch using the laws of physics

● Instead, they reuse standard designs with successful track records, learning from experience

● Should software engineers make use of patterns? Why?

● Developing software from scratch is also expensive


● Patterns support reuse of software architecture design

2/21/24 Dr. Amjad AbuHassan 3


Definitions and Names

● Alexander: “A pattern is a recurring solution to a standard problem, in


a context.”
● Larman: “In OO design, a pattern is a named description of a problem
and solution that can be applied in new contexts; ideally, a pattern
advises us on how to apply the solution in varying circumstances and
considers the forces and trade-offs.”

2/21/24 Dr. Amjad AbuHassan 4


Naming Patterns—important!

● Patterns have suggestive names:


● Arched Columns Pattern, Easy Toddler Dress Pattern, etc.
● Why is naming a pattern or principle helpful?
● It supports chunking and incorporating that concept into
our understanding and memory

● It facilitates communication

2/21/24 Dr. Amjad AbuHassan 5


Patterns/Principles aid Communication

Fred: "Where do you think we should place the responsibility for creating
a SalesLineltem? I think a Factory."

Wilma: "By Creator, I think Sale will be suitable."

Fred: "Oh, right - I agree."

2/21/24 Dr. Amjad AbuHassan 6


Well-known Pattern Families

● SOLID:
● Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation,
and Dependency Inversion

● GoF: Design Patterns: Elements of Reusable Object- Oriented Software


● GoF: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
● 23 patterns

2/21/24 Dr. Amjad AbuHassan 7


Gang of Four Design Patterns

Design Pattern Categories


● Creational patterns
● Structural Patterns
● Behavioral Patterns

2/21/24 Dr. Amjad AbuHassan 8


Creational Patterns
● Deal with the process of object creation
● Defer object creation to another object (Achieved through
association and interface)
● Singleton
● Factory Method
● Abstract Factory
● Builder
● Prototype
2/21/24 Dr. Amjad AbuHassan 9
Structural Patterns

● Deal with decoupling interface ● Façade


and implementation of classes ● Adapter
● Deal with how objects/classes can ● Bridge
be combined ● Composite
● Describe ways to assemble ● Decorator
objects ● Flyweight
● Proxy
2/21/24 Dr. Amjad AbuHassan 10
Behavioral Patterns
● Deal with communication between ● Template Method
objects and how the objects / classes
● Chain of Responsibility
distribute responsibility)
● Command
● Describes how a group of objects
● Iterator
cooperate to perform task that no
single object can complete alone ● Mediator

● Strategy ● Memento

● Observer ● State

● Interpreter ● Visitor
2/21/24 Dr. Amjad AbuHassan 11
Singleton Pattern

2/21/24 Dr. Amjad AbuHassan 12


Intent

● Singleton is a creational design


pattern that lets you ensure that
a class has only one instance,
while providing a global access
point to this instance.

2/21/24 Dr. Amjad AbuHassan 13


Problem

● The Singleton pattern solves two problems at the same time:


● Ensure that a class has just a single instance
● Provide a global access point to that instance
● Just like a global variable, the Singleton pattern lets you access some
object from anywhere in the program.
● However, it also protects that instance from being overwritten by other code.

2/21/24 Dr. Amjad AbuHassan 14


Single Instance
● The most common reason for this is to control access to some shared resource—
for example, a database or a file.

● Imagine that you created an object, but after a while decided to create a new one.
Instead of receiving a fresh object, you’ll get the one you already created.
● This behavior is impossible to implement with a regular constructor since a constructor
call must always return a new object by design.

2/21/24 Dr. Amjad AbuHassan 15


Single Instance cont.
Clients may not even
realize that they’re
working with the same
object all the time.

2/21/24 Dr. Amjad AbuHassan 16


Singleton Types
● Eager Initialization: creates the instance of the singleton class at the
time of class loading, before any other class uses it.
● This ensures that the singleton instance is always available.
● But this approach can be memory-intensive, as the instance is created before it
is needed.
● Lazy Initialization: creates the instance of the singleton class only
when it is needed.
● Can save memory if the singleton is not used very often.
2/21/24 Dr. Amjad AbuHassan 17
Solution Structure

2/21/24 Dr. Amjad AbuHassan 18


Solution

● Make the default constructor private, to prevent other objects from


using the new operator with the Singleton class.
● Create a static creation method that acts as a constructor. Under the
hood, this method calls the private constructor to create an object and
saves it in a static field.
● All following calls to this method return the cached object.

2/21/24 Dr. Amjad AbuHassan 19


Real-World Analogy

The government is an excellent example of the Singleton pattern. A


country can have only one official government. Regardless of the personal
identities of the individuals who form governments, the title, “The
Government of X”, is a global point of access that identifies the group of
people in charge.

2/21/24 Dr. Amjad AbuHassan 20


Example

2/21/24 Dr. Amjad AbuHassan 21


Example cont.

If you see the same value, then singleton was reused


If you see different values, then 2 singletons were created

RESULT:
FOO
FOO
2/21/24 Dr. Amjad AbuHassan 22
Applicability

● Use it when a class should have just a single instance for all clients.

● Use the Singleton pattern when you need stricter control over global
variables.
● Unlike global variables, Singleton guarantees that there’s just one instance
● But also you can adjust this limitation

2/21/24 Dr. Amjad AbuHassan 23


Facade Pattern

2/21/24 Dr. Amjad AbuHassan 24


Intent

● Facade is a structural design


pattern that provides a simplified
interface to a library, a
framework, or any other complex
set of classes.

2/21/24 Dr. Amjad AbuHassan 25


Problem

● Imagine that you must make your code work with a set of objects that
belong to a sophisticated library or framework.
● Ordinarily, you’d need to initialize all of objects, keep track of dependencies,
execute methods in the correct order, and so on.

● As a result, the business logic of the classes would become tightly coupled to
the implementation details of 3rd-party classes

2/21/24 Dr. Amjad AbuHassan 26


Solution

● A facade is a class that provides a simple interface to a complex


subsystem which contains lots of moving parts.

● In case you need to integrate your app with a sophisticated library that
has dozens of features, but you just need a tiny bit of its functionality.

2/21/24 Dr. Amjad AbuHassan 27


Solution Structure

2/21/24 Dr. Amjad AbuHassan 29


Real-World Analogy

When you call a shop to place a phone order, an operator is your facade
to all services and departments of the shop. The operator provides you
with a simple voice interface to the ordering system, payment gateways,
and various delivery services.

2/21/24 Dr. Amjad AbuHassan 30


Example

In this example, the Facade pattern simplifies interaction with a complex


notification service framework.

Send a push notification


// connect() -> Connection
// authenticate(appID, key) -> AuthToken
// send(authToken, message, target)
// [Link]()
2/21/24 Dr. Amjad AbuHassan 31
Example cont.

2/21/24 Dr. Amjad AbuHassan 32


Example cont.

2/21/24 Dr. Amjad AbuHassan 33


Example cont.

2/21/24 Dr. Amjad AbuHassan 34


Example Solution

2/21/24 Dr. Amjad AbuHassan 35


Example Solution cont.

2/21/24 Dr. Amjad AbuHassan 36


Example Solution cont.

2/21/24 Dr. Amjad AbuHassan 37


Applicability
Use it when you need a limited but straightforward interface to a complex subsystem.
● The Facade provides a shortcut to the most-used features of the subsystem which
fit most client requirements.
Use the Facade when you want to structure a subsystem into layers.
● Used to define entry points to each level of a subsystem, and this reduces coupling
between multiple subsystems by requiring them to communicate only through
facades.

2/21/24 Dr. Amjad AbuHassan 44


Adapter Pattern
Also Known as: Wrapper

4/2/22 Dr. Amjad AbuHassan 45


Intent

Adapter is a structural design


pattern that allows objects with
incompatible interfaces to
collaborate.

4/2/22 Dr. Amjad AbuHassan 46


Real-World Analogy

4/2/22 Dr. Amjad AbuHassan 47


Problem

● Suppose that you’re creating a stock market monitoring app. The app
downloads the stock data from multiple sources in XML format and then
displays nice-looking charts and diagrams for the user.
● At some point, you decide to improve the app by integrating a smart 3rd-
party analytics library.
● But there’s a catch: the analytics library only works with data in JSON format.

4/2/22 Dr. Amjad AbuHassan 48


Problem cont.

● You can’t use the analytics library “as is” because it expects the data
in a format that’s incompatible with your app.

4/2/22 Dr. Amjad AbuHassan 49


Problem cont.

You could change the library to work with XML.


● First, you might not have access to the library’s source code in the
first place, making this approach impossible.
● Even if you have access, this might break some existing code that
relies on the library.

4/2/22 Dr. Amjad AbuHassan 50


Solution
● Create an adapter: a special object that converts the interface of one object so that
another object can understand it.
● It wraps one of the objects to hide the complexity of conversion happening behind the scenes.

● The wrapped object isn’t even aware of the adapter.


● For example, you can wrap an object that operates in meters and kilometers with an
adapter that converts all of the data to imperial units such as feet and miles.
● Adapters can not only convert data into various formats but can also help objects with
different interfaces collaborate.

4/2/22 Dr. Amjad AbuHassan 51


How it Works
1. The adapter gets an interface, compatible with one of the existing objects.
2. Using this interface, the existing object can safely call the adapter’s methods.
3. Upon receiving a call, the adapter passes the request to the second object, but
in a format and order that the second object expects.
Sometimes it’s even possible to create a two-way adapter that can convert the
calls in both directions.

4/2/22 Dr. Amjad AbuHassan 52


Stock Market App

4/2/22 Dr. Amjad AbuHassan 53


Object Adapter Structure

4/2/22 Dr. Amjad AbuHassan 54


Example

In this example of the Adapter pattern, we want to build one of those


mobile apps for our applying pretty filters to our photos.

So, we can capture or load a photo, and then apply various filters to it.

4/2/22 Dr. Amjad AbuHassan 55


Example cont.

4/2/22 Dr. Amjad AbuHassan 56


Example cont.

4/2/22 Dr. Amjad AbuHassan 57


Example Problem

[Link](new Desert());
we have a compilation error here,

4/2/22 Dr. Amjad AbuHassan 58


Example Current Structure

4/2/22 Dr. Amjad AbuHassan 59


Example Solution

Desert Desert

4/2/22 Dr. Amjad AbuHassan 60


Example Solution cont.

4/2/22 Dr. Amjad AbuHassan 61


Applicability

Use it when there is some existing class, but its interface isn’t
compatible with our code.
● The pattern creates a middle-layer class that serves as a translator
between our code and a legacy class, a 3rd-party class or any other
class with a weird interface.

4/2/22 Dr. Amjad AbuHassan 68


Observer Pattern

2/21/24 Dr. Amjad AbuHassan 71


Intent

● Observer is a behavioral design


pattern that lets you define a
subscription mechanism to notify
multiple objects about any
events that happen to the object
they’re observing.

2/21/24 Dr. Amjad AbuHassan 72


Problem
● Suppose you have two types of objects: a Customer and a Store. The customer is
interested in a new brand of product which should be available in the store soon.
● The customer could visit the store every day and check product availability.
● Most of these trips would be pointless as the product is still in route.

● However, the store could send tons of emails to all customers each time a new
product becomes available.
● This would save some customers from endless trips to the store.

● At the same time, it’d upset other customers who aren’t interested in new products.

2/21/24 Dr. Amjad AbuHassan 73


Solution

● The object that has some interesting state is often called subject, but
since it’s also going to notify other objects about the changes to its
state, we’ll call it publisher.
● All other objects that want to track changes to the publisher’s state are
called subscribers.

2/21/24 Dr. Amjad AbuHassan 74


Solution cont.

● The Observer pattern suggests that you add a subscription mechanism


to the publisher class so individual objects can subscribe to or
unsubscribe from a stream of events coming from that publisher.

2/21/24 Dr. Amjad AbuHassan 75


Solution cont.
● Real apps might have dozens of different subscriber classes that are interested in
tracking events of the same publisher class.
● We don’t want to couple the publisher to all of those classes.

● Also, we might not even know about some of them beforehand

● So it’s crucial that all subscribers implement the same interface and that the
publisher communicates with them only via that interface.
● This interface should declare the notification method along with a set of parameters that the
publisher can use to pass some contextual data along with the notification.

2/21/24 Dr. Amjad AbuHassan 76


Solution cont.

Publisher notifies
subscribers by calling the
specific notification method
on their objects.

2/21/24 Dr. Amjad AbuHassan 77


Real-World Analogy
If you subscribe to a newspaper or magazine, you no longer need to go to the store to
check if the next issue is available. Instead, the publisher sends new issues directly to
your mailbox right after publication or even in advance.

The publisher maintains a list of subscribers and


knows which magazines they’re interested in.
Subscribers can leave the list at any time when
they wish to stop the publisher sending new
magazine issues to them.
2/21/24 Dr. Amjad AbuHassan 78
Structure

2/21/24 Dr. Amjad AbuHassan 79


Example

Suppose we have a list of values, and we have pie chart that is based on
these values, and we have another sheet where we display the total of
values
Now, if we change any of these values, the pie chart as well as the total
value will get updated immediately.
So, we have an object that notifies other objects about new changes

2/21/24 Dr. Amjad AbuHassan 80


Example cont.

2/21/24 Dr. Amjad AbuHassan 81


Example cont.

2/21/24 Dr. Amjad AbuHassan 82


Example cont.

2/21/24 Dr. Amjad AbuHassan 83


Example cont.

2/21/24 Dr. Amjad AbuHassan 84


Applicability
Use the Observer pattern when changes to the state of one object may require changing other
objects, and the actual set of objects is unknown beforehand or changes dynamically.
● The Observer pattern lets any object that implements the subscriber interface subscribe
for event notifications in publisher objects.
Use the pattern when some objects in your app must observe others, but only for a limited
time or in specific cases.
● The subscription list is dynamic, so subscribers can join or leave the list whenever they
need to.

2/21/24 Dr. Amjad AbuHassan 91


Factory Pattern
Also Known as: Virtual Constructor

4/2/22 Dr. Amjad AbuHassan 92


Intent
● Factory Method is a creational
design pattern that provides an
interface for creating objects in
a superclass, but allows
subclasses to alter the type of
objects that will be created.

4/2/22 Dr. Amjad AbuHassan 93


Problem
● Suppose that you’re creating a logistics management application.
The first version of your app can only handle transportation by
trucks, so the bulk of your code lives inside the Truck class.
● After a while, your app becomes popular. Each day you receive
dozens of requests from sea transportation companies to
incorporate sea logistics into the app.

4/2/22 Dr. Amjad AbuHassan 94


Problem cont.
● Adding a new class to the program isn’t that simple if the rest of the
code is already coupled to existing classes.

4/2/22 Dr. Amjad AbuHassan 95


Problem cont.

At present, most of your code is coupled to the Truck class.

Adding Ships into the app would require making changes to the entire codebase.

Moreover, if later you decide to add another type of transportation to the app, you
will probably need to make all of these changes again.

As a result, you will end up with pretty nasty code, riddled with conditionals that
switch the app’s behavior depending on the class of transportation objects.

4/2/22 Dr. Amjad AbuHassan 96


Solution

● The Factory Method pattern suggests that you replace direct object
construction calls (using the new operator) with calls to a special
factory method.
● Defer the creation of an object to subclasses
● Objects returned by a factory method are often referred to as
products.

4/2/22 Dr. Amjad AbuHassan 97


Solution cont.
Subclasses can alter the class of objects being returned by the factory method

4/2/22 Dr. Amjad AbuHassan 98


Solution cont.
All products must follow the same interface

4/2/22 Dr. Amjad AbuHassan 99


Solution cont.
As long as all product classes implement a common interface, you can pass
their objects to the client code without breaking it.

4/2/22 Dr. Amjad AbuHassan 100


Structure

4/2/22 Dr. Amjad AbuHassan 101


Example

Suppose we have a class called Shape that represents different


geometric shapes.
This class has a method called draw() that draws the shape on a canvas.
The Shape class also has subclasses called Circle, Square, and Rectangle
that represent specific shapes.

2/21/24 Dr. Amjad AbuHassan 102


Example cont.

2/21/24 Dr. Amjad AbuHassan 103


Example cont.

2/21/24 Dr. Amjad AbuHassan 104


Solution

2/21/24 Dr. Amjad AbuHassan 105


Solution cont.

2/21/24 Dr. Amjad AbuHassan 106


Solution cont.

2/21/24 Dr. Amjad AbuHassan 107


Applicability
● Use the Factory Method when you don’t know beforehand the
exact types and dependencies of the objects your code should work
with.
● Use the Factory Method when you want to provide users of your
library or framework with a way to extend its internal components.
● Use the Factory Method when you want to save system resources
by reusing existing objects instead of rebuilding them each time.
4/2/22 Dr. Amjad AbuHassan 108
Strategy Pattern

2/21/24 Dr. Amjad AbuHassan 109


Intent

● Strategy is 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.

2/21/24 Dr. Amjad AbuHassan 110


Problem

● Suppose that you are creating a navigation app for casual travelers.
The app was centered around a map which helped users quickly orient
themselves in any city.
● One of the most requested features for the app was automatic route
planning. A user should be able to enter an address and see the fastest
route to that destination displayed on the map.

2/21/24 Dr. Amjad AbuHassan 111


Problem cont.

● The first version of the app could only build the routes over roads.
● In the next update, you added an option to build walking routes. Right
after that, you added another option to let people use public transport
in their routes.
● Later you planned to add route building for cyclists. And even later,
another option for building routes through all of a city’s tourist
attractions.
2/21/24 Dr. Amjad AbuHassan 112
Problem cont.

● From a business perspective the app was


a success, however 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 class became too
hard to maintain.
2/21/24 Dr. Amjad AbuHassan 113
Problem cont.

● Any change to one of the algorithms, whether it was a simple bug fix or
a slight adjustment of the street score, 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.

2/21/24 Dr. Amjad AbuHassan 114


Solution

● The Strategy pattern suggests that you take a class that does
something specific in a lot of different ways and extract all these
algorithms into separate classes called strategies.
● The original class, called context, must have a field for storing a
reference to one of the strategies. The context delegates the work to a
linked strategy object instead of executing it on its own.

2/21/24 Dr. Amjad AbuHassan 115


Solution cont.
● The context isn’t responsible for selecting an appropriate algorithm for the job.
● The client passes the desired strategy to the context. In fact, the context doesn’t
know much about strategies. 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.
● This way the context becomes independent of concrete strategies, so you can add
new algorithms or modify existing ones without changing the code of the context
or other strategies.
2/21/24 Dr. Amjad AbuHassan 116
Route planning strategies

2/21/24 Dr. Amjad AbuHassan 117


Route planning strategies cont.
● 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 since its primary
job is to render a set of checkpoints on the map.
● The class has a method for switching the active routing strategy, so its clients, such as the
buttons in the user interface, can replace the currently selected routing behavior with
another one.
2/21/24 Dr. Amjad AbuHassan 118
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.

2/21/24 Dr. Amjad AbuHassan 119


Structure

2/21/24 Dr. Amjad AbuHassan 120


Example
Suppose that you decided to create a Calculator app. The app was centered around
a arithmetic operations. One of the requested features for the app was division.
In the next app update, you added an option to multiplication operation. Right after
that, you added another operation for addition.
The code of the calculator became very bloated. Each time you added a new
operation algorithm, the main class of the navigator doubled in size. At some point,
became too hard to maintain.

2/21/24 Dr. Amjad AbuHassan 121


Example cont.

2/21/24 Dr. Amjad AbuHassan 122


Example cont.

2/21/24 Dr. Amjad AbuHassan 123


Example cont.

2/21/24 Dr. Amjad AbuHassan 124


Applicability

Use Strategy pattern when you want to use different variants of an


algorithm within an object and be able to switch from one algorithm to
another during runtime.
● The Strategy pattern lets you indirectly alter the object’s behavior at
runtime by associating it with different sub-objects which can perform
specific sub-tasks in different ways.

2/21/24 Dr. Amjad AbuHassan 125


Applicability cont.

Use the Strategy when you have a lot of similar classes that only differ in
the way they execute some behavior.
● The Strategy pattern lets you extract the varying behavior into a
separate class hierarchy and combine the original classes into one,
thereby reducing duplicate code.

2/21/24 Dr. Amjad AbuHassan 126


Applicability cont.

Use the pattern to isolate the business logic of a class from the
implementation details of algorithms that may not be as important in the
context of that logic.
● The Strategy pattern lets you isolate the code, internal data, and
dependencies of various algorithms from the rest of the code. Various
clients get a simple interface to execute the algorithms and switch
them at runtime.
2/21/24 Dr. Amjad AbuHassan 127
Applicability cont.

Use the pattern when your class has a massive conditional operator that
switches between different variants of the same algorithm.
● The Strategy pattern lets you do away with such a conditional by
extracting all algorithms into separate classes, all of which implement
the same interface. The original object delegates execution to one of
these objects, instead of implementing all variants of the algorithm.

2/21/24 Dr. Amjad AbuHassan 128

You might also like