0% found this document useful (0 votes)
25 views99 pages

07 - SW Design - Design Patterns - Part3

The document discusses various structural design patterns in software design, including the Adapter, Bridge, Facade, and Proxy patterns. Each pattern is explained with its purpose, implementation details, and real-world examples to illustrate their use in managing complex systems and enhancing code maintainability. The document serves as a guide for understanding how to effectively apply these design patterns in software development.

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)
25 views99 pages

07 - SW Design - Design Patterns - Part3

The document discusses various structural design patterns in software design, including the Adapter, Bridge, Facade, and Proxy patterns. Each pattern is explained with its purpose, implementation details, and real-world examples to illustrate their use in managing complex systems and enhancing code maintainability. The document serves as a guide for understanding how to effectively apply these design patterns in software development.

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/ 99

Software Design Principles

07 Design Pattern– Part 3


Dr. Mostafa Elgendy
[email protected]
Agenda
▪ Structural Design Patterns

▪ Adapter Pattern

▪ Bridge Pattern

▪ Facade Pattern

▪ Proxy Pattern

▪ Behavioral Design Patterns

▪ Observer Pattern

▪ Summary

7-May-24 SOFTWARE DESIGN PRINCIPLES 2


Structural Design Patterns

7-May-24 SOFTWARE DESIGN PRINCIPLES 3


Structural Design Patterns
▪ Structural design pattern is a blueprint of how different
objects and classes are combined to form a bigger structure
for achieving multiple goals altogether.

▪ So, with the help structural design pattern we can target and
change a specific parts of the structure without changing the
entire structure.

7-May-24 SOFTWARE DESIGN PRINCIPLES 4


Types of structural design patterns
▪ Adapter Pattern

▪ Bridge Pattern

▪ Composite Pattern

▪ Decorator Pattern

▪ Facade Pattern

▪ Flyweight Pattern

▪ Proxy Pattern

7-May-24 SOFTWARE DESIGN PRINCIPLES 5


Adapter Pattern

7-May-24 SOFTWARE DESIGN PRINCIPLES 6


Adapter Pattern
▪ Is a structural design pattern that allows objects with
incompatible interfaces to collaborate.

7-May-24 SOFTWARE DESIGN PRINCIPLES 7


Problem (1/2)
▪ Imagine that you’re creating a stock market
monitoring app.
▪ The app downloads the stock data in XML format
and then displays charts and diagrams.

▪ If you decide to improve the app by


integrating a 3rd-party analytics library.
▪ The library only works with data in JSON format.

7-May-24 SOFTWARE DESIGN PRINCIPLES 8


Problem (2/2)
▪ You could change the library to work
with XML.

▪ This might break some existing code

▪ You might not have access to the library’s


source code.

7-May-24 SOFTWARE DESIGN PRINCIPLES 9


Solution (1/2)
▪ Adapter is a special object that converts the
interface of one object so that another
object can understand it.

▪ An adapter wraps one of the objects to hide


the complexity of conversion happening
behind the scenes.

7-May-24 SOFTWARE DESIGN PRINCIPLES 10


Solution (2/2)
▪ To solve the problem of incompatible formats,

▪ Create XML-to-JSON adapters for class of the


analytics library that your code works with directly.

▪ When an adapter receives a call, it translates the


incoming XML data into a JSON structure and passes
the call to the appropriate methods of a wrapped
analytics object.

7-May-24 SOFTWARE DESIGN PRINCIPLES 11


How to implement
▪ It uses object composition principle:

▪ The adapter implements the interface of


one object

▪ and wraps the other one.

7-May-24 SOFTWARE DESIGN PRINCIPLES 12


How to implement
▪ The Client contains the existing
business logic of the program.

▪ The Client Interface describes a


protocol that other classes must
follow to be able to collaborate with
the client code.

7-May-24 SOFTWARE DESIGN PRINCIPLES 13


How to implement
▪ The Service is some useful class (usually
3rd-party or legacy). The client can’t use
this class directly because it has an
incompatible interface.

▪ The Adapter is a class that work with both


the client and the service:

▪ It implements the client interface, while wrapping


the service object.

7-May-24 SOFTWARE DESIGN PRINCIPLES 14


Example 1
▪ The Adapter pretends to be a
round peg, with a radius equal to
a half of the square’s diameter
(in other words, the radius of the
smallest circle that can
accommodate the square peg).

7-May-24 SOFTWARE DESIGN PRINCIPLES 15


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 16


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 17


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 18


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 19


Example 1
▪ The Calculator class and its getArea() method
used to calculate the area of the rectangle.

▪ If you want to calculate the area of a triangle


through the getArea() method of the Calculator
class.

▪ You can make CalculatorAdapter for the


Triangle class and passed a triangle in its
getArea() method.

▪ In turn, the method treats the triangle like a


rectangle and calculates the area from the
getArea() method of the Calculator class.

7-May-24 SOFTWARE DESIGN PRINCIPLES 20


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 21


Bridge Pattern

7-May-24 SOFTWARE DESIGN PRINCIPLES 22


Bridge Pattern
▪ A structural design pattern that lets you split a large class or a set of
closely related classes into two separate hierarchies —abstraction
and implementation—which can be developed independently of each
other.

7-May-24 SOFTWARE DESIGN PRINCIPLES 23


Bridge Pattern
▪ Whenever we purchase any smartphone, we get a charger.

▪ The charger cable now-a-days can be separated


▪ We can use it to connect as USB cable to connect other devices.

7-May-24 SOFTWARE DESIGN PRINCIPLES 24


Problem (1/2)
▪ If you have a geometric Shape class with a
pair of subclasses: Circle and Square.
▪ You want to extend this class hierarchy to
incorporate colors, so you plan to create Red
and Blue shape subclasses.

▪ However, since you already have two


subclasses, you’ll need to create four class
combinations such as BlueCircle and
RedSquare..

7-May-24 SOFTWARE DESIGN PRINCIPLES 25


Problem (2/2)
▪ Adding new shape types and colors to the
hierarchy will grow it exponentially.
▪ For example, to add a triangle shape you’d need
to introduce two subclasses, one for each color.

▪ And after that, adding a new color would require


creating three subclasses, one for each shape
type.

▪ The further we go, the worse it becomes.

7-May-24 SOFTWARE DESIGN PRINCIPLES 26


Solution (1/3)
▪ This problem because we’re trying to extend the
shape classes in two independent dimensions:
▪ by form and by color.

▪ Bridge pattern attempts to solve this problem by:


▪ Switching from inheritance to the object composition.

▪ Extract one of the dimensions into a separate class


hierarchy.

7-May-24 SOFTWARE DESIGN PRINCIPLES 27


Solution (2/3)
▪ Following this approach

▪ We can extract the color-related code into its


own class with two subclasses: Red and
Blue.

▪ The Shape class then gets a reference field


pointing to one of the color objects.

7-May-24 SOFTWARE DESIGN PRINCIPLES 28


Solution (3/3)
▪ Following this approach
▪ Now the shape can delegate any color-related
work to the linked color object.

▪ That reference will act as a bridge between


the Shape and Color classes.

▪ Now

▪ Adding new colors won’t require changing


the shape hierarchy.

7-May-24 SOFTWARE DESIGN PRINCIPLES 29


How to implement (1/3)
▪ Abstraction: provides high-level
control logic. It relies on the
implementation object to do the actual
low-level work.

7-May-24 SOFTWARE DESIGN PRINCIPLES 30


How to implement (2/3)
▪ Implementation: declares the interface
that’s common for all concrete
implementations.

▪ An abstraction can only communicate with


an implementation object via methods that
are declared here.

▪ Concrete Implementations: contain


platform specific code.

7-May-24 SOFTWARE DESIGN PRINCIPLES 31


How to implement (3/3)
▪ Refined Abstractions: provide variants of control
logic.
▪ Like their parent, they work with different
implementations via the general implementation
interface.

▪ Client: is only interested in working with the


abstraction.

▪ However, it’s the client’s job to link the abstraction


object with one of the implementation objects.

7-May-24 SOFTWARE DESIGN PRINCIPLES 32


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 33


Example 1
▪ This example illustrates how the Bridge pattern can
help divide the monolithic code of an app that manages
devices and their remote controls.

▪ The Device classes act as the implementation, whereas


the Remotes act as the abstraction.

▪ The base remote control class declares a reference


field that links it with a device object.
▪ All remotes work with the devices via the general device
interface, which lets the same remote support multiple device
types.

7-May-24 SOFTWARE DESIGN PRINCIPLES 34


Example 1
▪ You can develop the remote control classes
independently from the device classes.
▪ All that’s needed is to create a new remote subclass.

▪ For example, a basic remote control might only have


two buttons, but you could extend it with additional
features, such as an extra battery or a touchscreen.

▪ The client code links the desired type of


remote control with a specific device object via
the remote’s constructor.

7-May-24 SOFTWARE DESIGN PRINCIPLES 35


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 36


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 37


Example 2
▪ On the left-hand side, you can see the abstraction
layer. Let’s say you want to send a message to the
corresponding person.

▪ On the right-hand side, you can see two


implementations. You can Email the message or SMS
the message to the corresponding person.

▪ So, you have two options to send the message and


the abstraction will use one of the implementations to
send the message to the corresponding person.

7-May-24 SOFTWARE DESIGN PRINCIPLES 38


Example 2

7-May-24 SOFTWARE DESIGN PRINCIPLES 39


Example 3
▪ Assume we need to store in 2 different storage mechanisms file and
database.

▪ Normally we go with separate classes to do these processes as shown


below:

7-May-24 SOFTWARE DESIGN PRINCIPLES 40


Example 3
▪ Assume we need to add code to do the same thing for course object also.

▪ Then we will need two more classes like SaveCourseInFile and SaveCourseInDB.

7-May-24 SOFTWARE DESIGN PRINCIPLES 41


Example 4
▪ A Vehicle Paint Shop which provides services such as Painting and Polishing.

▪ Different types of vehicles come to the shop.

▪ In this case, has to decouple the vehicles and shop services

7-May-24 SOFTWARE DESIGN PRINCIPLES 43


Example 5
▪ We have a DrawAPI interface which is
acting as a bridge implementer and
concrete classes RedCircle, GreenCircle
implementing the DrawAPI interface.

▪ Shape is an abstract class and will use


object of DrawAPI.

▪ BridgePatternDemo, our demo class will


use Shape class to draw different colored
circle.

7-May-24 SOFTWARE DESIGN PRINCIPLES 44


Facade Pattern

7-May-24 SOFTWARE DESIGN PRINCIPLES 45


Facade Pattern
▪ A structural design pattern that provides a simplified
interface to a library, a framework, or any other complex set
of classes.

7-May-24 SOFTWARE DESIGN PRINCIPLES 46


Facade Pattern

7-May-24 SOFTWARE DESIGN PRINCIPLES 47


Facade Pattern

7-May-24 SOFTWARE DESIGN PRINCIPLES 48


Problem
▪ Imagine your code work with a broad set of objects that belong to
a sophisticated library or framework.
▪ you need to initialize all of those objects, keep track of dependencies,
execute methods in the correct order, and so on.

▪ As a result:
▪ Business logic of your classes would become tightly coupled to the
implementation details of 3rd-party classes, making it hard to
comprehend and maintain.

7-May-24 SOFTWARE DESIGN PRINCIPLES 49


Solution
▪ A facade is a class that provides a simple interface to a complex subsystem
▪ A facade might provide limited functionality in comparison to working with the
subsystem directly. However, it includes only those features that clients really care
about.

▪ Ex: an app that uploads short funny videos to social media could potentially
use a professional video conversion library.
▪ However, all that it really needs is a class with the single method encode(filename,
format).

▪ After creating such a class and connecting it with the video conversion library, you’ll
have your first facade.

7-May-24 SOFTWARE DESIGN PRINCIPLES 50


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.

7-May-24 SOFTWARE DESIGN PRINCIPLES 51


How to implement
▪ The Facade provides convenient access to a
particular part of the subsystem’s functionality.
▪ It knows where to direct the client’s request and how
to operate all the moving parts.

▪ An Additional Facade class can be created to


prevent polluting a single facade with
unrelated features that might make it complex
structure.

7-May-24 SOFTWARE DESIGN PRINCIPLES 52


How to implement
▪ The Complex Subsystem consists of dozens of various
objects.
▪ They contains the implementation details, such as initializing
objects in the correct order.

▪ Subsystem classes aren’t aware of the facade’s


existence.
▪ They operate within the system and work with each other
directly.

▪ The Client uses the facade instead of calling the


subsystem objects directly.

7-May-24 SOFTWARE DESIGN PRINCIPLES 53


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 54


Example 1
▪ Instead of making your code work with dozens of the
framework classes directly, you create a facade class
which encapsulates that functionality and hides it
from the rest of the code.

▪ This structure also helps you to minimize the effort of


upgrading to future versions of the framework or
replacing it with another one.

▪ The only thing you’d need to change in your app


would be the implementation of the facade’s
methods.

7-May-24 SOFTWARE DESIGN PRINCIPLES 55


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 56


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 57


Example 2

7-May-24 SOFTWARE DESIGN PRINCIPLES 58


Proxy Pattern

7-May-24 SOFTWARE DESIGN PRINCIPLES 59


Proxy Pattern
▪ A structural design pattern that lets you provide a substitute or placeholder for
another object.

▪ A proxy controls access to the original object, allowing you to perform something
either before or after the request gets through to the original object.

7-May-24 SOFTWARE DESIGN PRINCIPLES 60


Problem
▪ Why would you want to control access to an object?

▪ Here is an example: you have a massive object that consumes a


vast amount of system resources.

▪ You need it from time to time, but not always.

7-May-24 SOFTWARE DESIGN PRINCIPLES 61


Solution
▪ The Proxy pattern suggests that you create a new proxy class with the same
interface as an original service object.

▪ Then you update your app so that it passes the proxy object to all of the
original object’s clients.

▪ Upon receiving a request from a client, the proxy creates a real service
object and delegates all the work to it.

7-May-24 SOFTWARE DESIGN PRINCIPLES 62


How to implement
▪ The Service Interface declares the
interface of the Service. The proxy must
follow this interface to be able to disguise
itself as a service object.

▪ The Service is a class that provides some


useful business logic.

7-May-24 SOFTWARE DESIGN PRINCIPLES 63


How to implement
▪ The Proxy class has a reference field that points
to a service object.
▪ After the proxy finishes its processing (e.g., lazy
initialization, logging, access control, caching, etc.), it
passes the request to the service object.

▪ Usually, proxies manage the full lifecycle of their


service objects.

▪ The Client should work with both services and


proxies via the same interface.

7-May-24 SOFTWARE DESIGN PRINCIPLES 64


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 65


Example 1
▪ The library provides us with the video downloading
class.
▪ If the client application requests the same video multiple
times, the library just downloads it over and over, instead of
caching and reusing the first downloaded file.

▪ The proxy class implements the same interface as the


original downloader and delegates it all the work.
▪ However, it keeps track of the downloaded files and returns
the cached result when the app requests the same video
multiple times.

7-May-24 SOFTWARE DESIGN PRINCIPLES 66


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 67


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 68


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 69


Example 2

7-May-24 SOFTWARE DESIGN PRINCIPLES 70


Example 2

7-May-24 SOFTWARE DESIGN PRINCIPLES 71


Example 2

7-May-24 SOFTWARE DESIGN PRINCIPLES 72


Behavioral Design Patterns

7-May-24 SOFTWARE DESIGN PRINCIPLES 73


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

7-May-24 SOFTWARE DESIGN PRINCIPLES 74


Observer Pattern

7-May-24 SOFTWARE DESIGN PRINCIPLES 75


Observer Pattern
▪ Also known as: Event-Subscriber, Listener.

▪ Lets you define a subscription mechanism to notify multiple objects


about any events that happen to the object they’re observing.

7-May-24 SOFTWARE DESIGN PRINCIPLES 76


Problem (1/2)
▪ Imagine that you have two types of objects: a
Customer and a Store.
▪ The customer is very interested in a particular brand of
product (say, it’s a new model of the iPhone) which
should become available in the store very soon.

▪ The customer could visit the store every day and check
product availability.

▪ But while the product is still in route, most of these trips


would be pointless.

7-May-24 SOFTWARE DESIGN PRINCIPLES 77


Problem (2/2)
▪ 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.

▪ It looks like we’ve got a conflict. Either the customer


wastes time checking product availability or the store
wastes resources notifying the wrong customers.

7-May-24 SOFTWARE DESIGN PRINCIPLES 78


Solution(1/3)
▪ The object that is going to notify other objects
about the changes to its state, is called
publisher.

▪ All other objects that want to track changes to the


publisher’s state are called subscribers.

▪ The Observer pattern suggests that you add a


subscription mechanism to the publisher class
▪ Individual objects can subscribe to or unsubscribe from a
stream of events from publisher.

7-May-24 SOFTWARE DESIGN PRINCIPLES 79


Solution(2/3)
▪ This mechanism consists of
▪ An array field for storing a list of references to
subscriber objects

▪ Several public methods which allow adding


subscribers to and removing them from that list.

▪ When an event happens to the publisher


▪ It goes over its subscribers and calls the specific
notification method on their objects.

7-May-24 SOFTWARE DESIGN PRINCIPLES 80


Solution(3/3)
▪ Real apps might have different subscriber.

▪ It’s crucial that all subscribers implement the


same interface

▪ The publisher communicates with them only


via that interface.

▪ This interface should declare the notification


method.

7-May-24 SOFTWARE DESIGN PRINCIPLES 81


Real-World Analogy
▪ If you subscribe to a newspaper, no longer
need to and check if the next issue is available.
▪ Instead, the publisher sends new issues directly to
your mailbox.

▪ The publisher maintains a list of subscribers


and knows which magazines they interested in.

▪ Subscribers can leave the list at any time when


they wish to stop the publisher sending new
magazine.

7-May-24 SOFTWARE DESIGN PRINCIPLES 82


How to implement (1/3)
▪ The Publisher issues events of interest to
other objects.
▪ These events occur when the publisher changes
its state or executes some behaviors.

▪ Publishers contain an infrastructure to lets new


subscribers join and current subscribers leave.

▪ When a new event happens


▪ Publisher goes over the subscription list and calls
the notification method.

7-May-24 SOFTWARE DESIGN PRINCIPLES 83


How to implement (2/3)
▪ The Subscriber interface declares the
notification interface.
▪ In most cases, it consists of a single update
method.

▪ Concrete Subscribers perform some actions


in response to notifications issued by the
publisher.
▪ All of these classes must implement the same
interface so the publisher isn’t coupled to concrete
classes.

7-May-24 SOFTWARE DESIGN PRINCIPLES 84


How to implement (3/3)
▪ The Client creates publisher and
subscriber objects separately and
then registers subscribers for
publisher updates.

7-May-24 SOFTWARE DESIGN PRINCIPLES 85


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 86


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 87


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 88


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 89


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 90


Example 2

7-May-24 SOFTWARE DESIGN PRINCIPLES 91


Example 2

7-May-24 SOFTWARE DESIGN PRINCIPLES 92


Example 2

7-May-24 SOFTWARE DESIGN PRINCIPLES 93


Example 3

7-May-24 SOFTWARE DESIGN PRINCIPLES 94


Example 3

7-May-24 SOFTWARE DESIGN PRINCIPLES 95


Example 1

7-May-24 SOFTWARE DESIGN PRINCIPLES 96


Example 3

7-May-24 SOFTWARE DESIGN PRINCIPLES 97


Example 3

7-May-24 SOFTWARE DESIGN PRINCIPLES 98


Summary
▪ Structural Design Patterns

▪ Adapter Pattern

▪ Bridge Pattern

▪ Facade Pattern

▪ Proxy Pattern

▪ Behavioral Design Patterns

▪ Observer Pattern

7-May-24 MOBILE PROGRAMMING 99


Questions

7-May-24 MOBILE PROGRAMMING 100

You might also like