You are on page 1of 45

OBJECT ORIENTED ANALYSIS DESIGN

Module Number: 05

Module Name: Design Patterns


Contents
1. Definition of Design Patterns
2. Types of Patterns:
Singleton
Factory
Builder
Prototype
Bridge
Adapter
Façade
Proxy
Composite
Strategy
State
Observer
Mediator, etc
3. 3. Case Study- Modeling ATM, e-shop, Cruise Control System, cellular network
Design Patterns
� A design pattern is a general repeatable solution to a commonly occurring problem in software
design.
� A design pattern isn't a finished design that can be transformed directly into code.
� It is a description or template for how to solve a problem that can be used in many different
situations.
Uses of Design Patterns
� Design patterns can speed up the development process by providing tested, proven development
paradigms.
� Effective software design requires considering issues that may not become visible until later in
the implementation.
� Reusing design patterns helps to prevent subtle issues that can cause major problems and
improves code readability for coders and architects familiar with the patterns.
� In addition, patterns allow developers to communicate using well-known, well understood
names for software interactions.
� Common design patterns can be improved over time, making them more robust than ad-hoc
designs.
� Patterns are primarily categorized as:
• Creational
• Structural
• Behavioral

Creational design patterns


• These design patterns are all about class instantiation.
• This pattern can be further divided into
✔ class-creation 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.
When to use Creational Design Patterns
� Complex Object Creation: Use creational patterns when the process of creating an object is
complex, involving multiple steps, or requires the configuration of various parameters.
� Promoting Reusability: Creational patterns promote object creation in a way that can be
reused across different parts of the code or even in different projects, enhancing modularity
and maintainability.
� Reducing Coupling: Creational patterns can help reduce the coupling between client code and
the classes being instantiated, making the system more flexible and adaptable to changes.
� Singleton Requirements: Use the Singleton pattern when exactly one instance of a class is
needed, providing a global point of access to that instance.
� Step-by-Step Construction: Builder pattern of creational design patterns is suitable when you
need to construct a complex object step by step, allowing for the creation of different
representations of the same object.
Advantages of Creational Design Patterns
Flexibility and Adaptability
Reusability
Centralized Control
Scalability
Promotion of Good Design Practices:
Creational patterns often encourage adherence to good design principles such as abstraction,
encapsulation, and the separation of concerns.
This leads to cleaner, more maintainable code.
Disadvantages of Creational Design Patterns
Increased Complexity: when dealing with a large number of classes, interfaces, and relationships.
Overhead: Using certain creational patterns, such as the Abstract Factory or Prototype pattern, may
introduce overhead due to the creation of a large number of classes and interfaces.
Dependency on Patterns: makes it challenging to adapt to changes or switch to alternative
solutions.
Readability and Understanding: The use of certain creational patterns might make the code less
readable and harder to understand, especially for developers who are not familiar with the specific
pattern being employed.
• Abstract Factory
Creates an instance of several families of classes
• Builder
Separates object construction from its representation
• Factory Method
Creates an instance of several derived classes
• If you have designed any object that is responsible for creating and maintaining the lifecycle of another
object, you have used the Factory pattern.
• Obtaining a database connection in your application using a connection manager or connection factory
object is a good example of the Factory pattern.
• Object Pool
Avoid expensive acquisition and release of resources by recycling objects that are no longer in use
•Prototype
A fully initialized instance to be copied or cloned.

•Prototype pattern refers to creating duplicate object while keeping performance in mind.

•This pattern involves implementing a prototype interface which tells to create a clone of the current
object. This pattern is used when creation of object directly is costly.

•For example, a object is to be created after a costly database operation.


•We can cache the object, returns its clone on next request and update the database as as and when
needed thus reducing database calls.

•Singleton
A class of which only a single instance can exist.

•A singleton is another example of a factory pattern.


•What makes the Singleton pattern unique is that one and only one instance of the object can exist irrespective
of the number of times the object is instantiated.

• The most common use of a Singleton pattern is for server applications like a Java based Remote Method
Invocation (RMI) server application.
Structural design patterns
� These design patterns are all about Class and Object composition.
� Structural class-creation patterns use inheritance to compose interfaces.
� Structural object-patterns define ways to compose objects to obtain new
functionality.
When to use Structural Design Patterns
Adapting to Interfaces: Use structural patterns like the Adapter pattern when you need to make
existing classes work with others without modifying their source code.
Organizing Object Relationships: Structural patterns such as the Decorator pattern are useful
when you need to add new functionalities to objects by composing them in a flexible and reusable
way, avoiding the need for subclassing.
Simplifying Complex Systems: When dealing with complex systems, structural patterns like the
Facade pattern can be used to provide a simplified and unified interface.
Managing Object Lifecycle: The Proxy pattern is helpful when you need to control access to an
object, either for security purposes, to delay object creation, or to manage the object’s lifecycle.
Hierarchical Class Structures: The Composite pattern is suitable when dealing with hierarchical
class structures where clients need to treat individual objects and compositions of objects
uniformly.
Advantages of Structural Design Patterns
❖ Flexibility and Adaptability Disadvantages of Structural Design Patterns
❖ Complexity
❖ Code Reusability
❖ Overhead
❖ Simplified Integration
❖ Maintenance Challenges
❖ Easier Maintenance:
❖ Limited Applicability
❖ Solves Recurring Design Problems
• Adapter
Match interfaces of different classes
• Bridge
Separates an object’s interface from its implementation
• Composite
A tree structure of simple and composite objects
• Facade
A single class that represents an entire subsystem
• Proxy
An object representing another object
• Decorator
Decorator pattern allows to add new functionality an existing object without altering its structure

• Flyweight Pattern
Flyweight pattern is primarily used to reduce the number of objects created, to decrease memory footprint and increase performance
• Adapter
Match interfaces of different classes
• In the Adapter pattern, an object provides an implementation of an interface used by other objects in a
consistent way.

� Adapter pattern works as a bridge between two incompatible interfaces.

� This pattern involves a single class which is responsible to join functionalities of independent or incompatible
interfaces.

A real life example could be a case of card reader which acts as an adapter between memory card and a laptop.

� You plugins the memory card into card reader and card reader into the laptop so that memory card can be read
via laptop.

� We are demonstrating use of Adapter pattern via following example in which an audio player device can play
mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files.
•Proxy
An object representing another object
•A Proxy pattern constitutes use of proxy objects during object interaction.
•A proxy object acts as a substitute for the actual object.
•Use of proxy objects is prevalent in remote object interaction protocols.

As an example, when an object needs to interact with a remote object, say across a network, the most
preferred way of encapsulating and hiding the interaction mechanism is by using a proxy object that
mediates communication between the requesting object and the remote object.
Composite Pattern
� Composite pattern is used where we need to treat a group of objects in
similar way as a single object.

� Composite pattern composes objects in term of a tree structure to


represent part as well as whole hierarchy .

� This pattern creates a class contains group of its own objects. This class
provides ways to modify its group of same objects.

� We are demonstrating use of Composite pattern via following example in


which show employees hierarchy of an organization.
Decorator Pattern
� Decorator pattern allows to add new functionality an existing object
without altering its structure.
� This type of design pattern comes under structural pattern as this
pattern acts as a wrapper to existing class.
� This pattern creates a decorator class which wraps the original class and
provides additional functionality keeping class methods signature
intact.
� We are demonstrating use of Decorator pattern via following example in
which we'll decorate a shape with some color without alter shape
class.

https://www.tutorialspoint.com/design_pattern/design_pattern_quick_guide.htm
Bridge Pattern
� Bridge is used where we need to decouple an abstraction from its
implementation so that the two can vary independently.
� This type of design pattern comes under structural pattern as this
pattern decouples implementation class and abstract class by providing
a bridge structure between them.
� This pattern involves an interface which acts as a bridge which
makes the functionality of concrete classes independent from interface
implementer classes.
� Both types of classes can be altered structurally without affecting each
other.
� We are demonstrating use of Bridge pattern via following example in
which a
circle can be drawn in different colors using same abstract class method
but different bridge implementer classes.
Facade Pattern
� Facade pattern hides the complexities of the system and provides an
interface to the client using which the client can access the system.
� This type of design pattern comes under structural pattern as this
pattern adds an interface to exiting system to hide its
complexities.
� This pattern involves a single class which provides simplified
methods which are required by client and delegates calls to existing
system
Flyweight Pattern
� Flyweight pattern is primarily used to reduce the number of objects
created, to decrease memory footprint and increase performance.

� This type of design pattern comes under structural pattern as this pattern
provides ways to decrease objects count thus improving application required
objects structure.

� Flyweight pattern try to reuse already existing similar kind objects by


storing them and creates new object when no matching object is found.

We'll demonstrate this pattern by drawing 20 circle of different locations but we'll
creating only 5 objects.

� Only 5 colors are available so color property is used to check already


existing Circle objects.
Behavioral design patterns
� These design patterns are all about Class's objects communication.
� Behavioral patterns are those patterns that are most specifically concerned with
communication between objects.

❖ Musicians are examples of Interpreters.

❖ The pitch of a sound and its duration can be


represented in musical notation on a staff.

❖ This notation provides the language of


music.
❖ Musicians playing the music from the score
are able to reproduce the original pitch and
duration of each sound represented.
When to use Behavioral Design Patterns
Communication Between Objects: Use behavioral patterns when you want to define how objects
communicate, collaborate, and interact with each other in a flexible and reusable way.
Encapsulation of Behavior: Apply behavioral patterns to encapsulate algorithms, strategies, or
behaviors, allowing them to vary independently from the objects that use them. This promotes code
reusability and maintainability.
Dynamic Behavior Changes: Use behavioral patterns when you need to allow for dynamic changes
in an object’s behavior at runtime without altering its code. This is particularly relevant for systems
that require flexibility in behavior.
State-Dependent Behavior: State pattern is suitable when an object’s behavior depends on its
internal state, and the object needs to change its behavior dynamically as its state changes.
Interactions Between Objects: Behavioral patterns are valuable when you want to model and
manage interactions between objects in a way that is clear, modular, and easy to understand.
Advantages of Behavioral Design Patterns
Flexibility and Adaptability:
Behavioral patterns enhance flexibility by allowing objects to interact in a more dynamic and adaptable way.
This makes it easier to modify or extend the behavior of a system without altering existing code.
Code Reusability:
Behavioral patterns promote code reusability by encapsulating algorithms, strategies, or behaviors in separate
objects.
This allows the same behavior to be reused across different parts of the system.
Separation of Concerns:
These patterns contribute to the separation of concerns by dividing the responsibilities of different classes,
making the codebase more modular and easier to understand.
Encapsulation of Algorithms:
Behavioral patterns encapsulate algorithms, strategies, or behaviors in standalone objects, making it possible to
modify or extend the behavior without affecting the client code.
Ease of Maintenance:
With well-defined roles and responsibilities for objects, behavioral patterns contribute to easier maintenance.
Changes to the behavior can be localized, reducing the impact on the rest of the code.
Disadvantages of Behavioral Design Patterns
Increased Complexity: Introducing behavioral patterns can sometimes lead to increased complexity in
the codebase, especially when multiple patterns are used or when there is an excessive use of design
patterns in general.
Over-Engineering: There is a risk of over-engineering when applying behavioral patterns where
simpler solutions would suffice.
Overuse of patterns may result in code that is more complex than necessary.
Limited Applicability: Not all behavioral patterns are universally applicable. The suitability of a
pattern depends on the specific requirements of the system, and using a pattern in the wrong context
may lead to unnecessary complexity.
Code Readability: In certain cases, applying behavioral patterns may make the code less readable and
harder to understand, especially for developers who are not familiar with the specific pattern being
employed.
Scalability Concerns: As the complexity of a system increases, the scalability of certain behavioral
patterns may become a concern.
• Command
Encapsulate a command request as an object
• The Command pattern is commonly used for gathering requests
from client objects and packaging them into a single object for
processing.
• The Command pattern allows for having well defined command
interfaces that are implemented by the object that provides the
processing for the client requests packaged as commands.
•Null Object
• Interpreter
A way to include language elements in a program Designed to act as a default value of an object
•Observer
• Iterator
Sequentially access the elements of a collection A way of notifying change to a number of classes
•State
• A simple mechanism to traverse and access a list of objects is defined
by the Iterator pattern. The Iterator pattern encapsulates the internal Alter an object's behavior when its state changes
implementation of the list while providing a standardized mechanism •Strategy
for list traversal. Encapsulates an algorithm inside a class
• Mediator •Template method
Defines simplified communication between classes Defer the exact steps of an algorithm to a subclass
• Memento •Visitor
Capture and restore an object's internal state Defines a new operation to a class without change
Command Pattern
� Command pattern is a data driven design pattern and falls under
behavioral pattern category.
� A request is wrapped under a object as command and passed 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.
Interpreter Pattern
� Interpreter pattern provides way to evaluate language grammar or
expression.
� This type of pattern comes under behavioral patterns.
� This pattern involves implementing a expression interface which tells to
interpret a particular context.
� This pattern is used in SQL parsing, symbol processing engine etc.
Iterator Pattern
� Iterator pattern is very commonly used design pattern in Java and .Net
programming environment.
� This pattern is used to get a way to access the elements of a
collection object in sequential manner without any need to know
its underlying representation.
� Iterator pattern falls under behavioral pattern category.
Mediator Pattern
� 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.
� Mediator pattern falls under behavioral pattern category.

Memento Pattern
Observer Pattern Memento pattern is used to reduce where we
Observer pattern is used when there is one to want to restore state of an object to a previous
many relationship between objects such as if one state.
object is modified, its depenedent objects are to be
notified automatically.
Memento pattern falls under behavioral pattern
category.
Observer pattern falls under behavioral pattern
category.
State Pattern
� In State pattern a class behavior changes based on its state. This type
of design pattern comes under behavior pattern.
� In State pattern, we create objects which represent various states and a
context object whose behavior varies as its state object changes.

Template Pattern
In Template pattern, an abstract class exposes defined way(s)/template(s) to
execute its methods.

Its subclasses can overrides the method implementations as per need basis
but the invocation is to be in the same way as defined by an abstract class.
This pattern comes under behavior pattern category.
Strategy Pattern
In Strategy pattern, a class behavior or its algorithm can be changed at run
time. This type of design pattern comes under behavior pattern.

In Strategy pattern, we create objects which represent various strategies and a


context object whose behavior varies as per its strategy object.

The strategy object changes the executing algorithm of the context object.
Visitor Pattern
� In Visitor pattern, we use a visitor class which changes the executing
algorithm of an element class.
� By this way, execution algorithm of element can varies as visitor varies.
This pattern comes under behavior pattern category.
� As per the pattern, element object has to accept the visitor object so
that visitor object handles the operation on the element object.
MVC Pattern
� MVC Pattern stands for Model-View-Controller Pattern. This pattern is
used to separate application's concerns.
• Model - Model represents an object or JAVA POJO carrying data. It
can also have logic to update controller if its data changes.
• View - View represents the visualization of the data that model
contains.
• Controller - Controller acts on both Model and view. It controls the
data flow into model object and updates the view whenever data
changes. It keeps View and Model separate.
CASE STUDIES
ATM Modelling:

• The Object-Oriented Modelling assists the programmer to address the complexity of a problem domain
by considering the problem not as a set of functions that can be performed but primarily as a set of
related, interacting Objects.

• This Modelling is based on the approach of Object-Oriented Modelling through Unified Modelling
Language (UML) for an ATM system in the Banking sector.
• The main aim of this Modelling is to provide a flexible and faithful environment for a customer, who
wants to do online banking transactions.
• After successful authentication, the customer can withdraw the desired amount (within the prescribed
limit) from the ATM machine or can transfer amount to another account. A user can also change the pin
code.
• The ATM has solved many problems, and now the customer can have money transaction 24/7. In this
article UML Class, Interaction diagram, Activity diagram and Use Case diagram are also designed for
the ATM System.

https://www.startertutorials.com/uml/category/case-studies 33
ATM Modelling:

Class diagram for ATM


34
Fig: Sequence diagram for ATM
35
Fig: Use case for ATM 36
•Web Customer actor uses some web site to make purchases
online.
•Top level use cases are View Items, Make
E-shop:
Purchase and Client Register.
•View Items use case could be used by customer as top level
use case if customer only wants to find and see some
products.
•This use case could also be used as a part of Make Purchase
use case.
•Client Register use case allows customer to register on the
web site, for example to get some coupons or be invited to
private sales. Note, that Checkout use case is included use
case not available by itself - checkout is part of making
purchase.
•Except for the Web Customer actor there are several other
Fig: use case
actors which will be described below with detailed use cases.37
•View Items use case is extended by several optional
use cases - customer may search for items, browse
catalog, view items recommended for him/her, add
items to shopping cart or wish list.
•All these use cases are extending use cases because
they provide some optional functions allowing
customer to find item.
•Customer Authentication use case
is included in View Recommended Items and Add
to Wish List because both require the customer to
be authenticated.
•At the same time, item could be added to the
shopping cart without user authentication.

38
Checkout use case also includes Payment use case
which could be done either by using credit card and
external credit payment service or with PayPal.

39
What is cruise control?
•The purpose of a cruise control system is to accurately maintain a speed set by the driver without any
outside intervention by controlling the throttle-accelerator pedal linkage.

•The earliest variants of cruise control were actually in use even before the creation of automobiles.

•The inventor and mechanical engineer James Watt developed a version as early as the 17th century,
which allowed steam engines to maintain a constant speed up and down inclines.

•Cruise control as we know it today was invented in the late 1940s, when the idea of using an
electrically-controlled device that could manipulate road speeds and adjust the throttle accordingly
was conceived.

40
How does cruise control work?
•The cruise control system controls the speed of your car the same way
you do – by adjusting the throttle (accelerator) position.

•However, cruise control engages the throttle valve by a cable


connected to an actuator, rather than by pressing a pedal.

•The throttle valve controls the power and speed of the engine by
limiting how much air it takes in (since it’s an internal combustion
engine).

41
•The driver can set the cruise control with the cruise switches, which usually consist of ON,
OFF, RESUME, SET/ACCEL and COAST.
•These are commonly located on the steering wheel or on the windshield wiper or turn signal
stalk.
•The SET/ACCEL knob sets the speed of the car.
•One tap will accelerate it by 1 mph, two by 2 mph and so on.
•Tapping the knob in the opposite direction will decelerate the vehicle.
•As a safety feature, the cruise control system will disengage as soon as you hit the brake
pedal.

42
Fig: Class diagram
43
cellular network

Fig: Use case for Cellular Network


44
THANK YOU

You might also like