0% found this document useful (0 votes)
10 views

UIT2301 Design Patterns Unit 4

Uploaded by

sidu2005mi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

UIT2301 Design Patterns Unit 4

Uploaded by

sidu2005mi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Design Patterns

Definition
• A design pattern is a generic repeatable solution to a frequently
occurring problem in software design that is used in software
engineering.
• It isn’t a complete design that can be written in code right away.
• It is a description or model for problem-solving that may be applied in
a variety of contexts.
Types of Software Design Patterns in Python
1.Creational Design Patterns
2. Structural Design Patterns
3. Behavioral Design Patterns
Creational Design Patterns
Structural Design Patterns
Behavioral Design Patterns
When to use Design Patterns

• Recurring Problems: Use design patterns when you encounter recurring design
problems that have well-established solutions. Design patterns provide tested and
proven approaches to common software design challenges.
• Flexibility and Reusability: Use design patterns to promote code reusability, flexibility,
and maintainability. They help in structuring code in a way that makes it easier to
modify and extend as requirements evolve.
• Design Principles: Use design patterns to apply fundamental design principles such as
separation of concerns, encapsulation, and dependency inversion. They help in
achieving better modularity and reducing dependencies between components.
• Communication: Use design patterns to improve communication among team
members. Design patterns provide a common vocabulary and understanding of how to
solve particular problems, facilitating collaboration and code comprehension.
• Performance: In some cases, design patterns can improve performance by optimizing
resource usage, reducing overhead, or improving code execution efficiency.
Singleton Design Pattern
Class Diagram
Code
class Singleton:
__instance = None
@staticmethod
def getInstance():
""" Static access method. """
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def __init__(self):
""" Virtually private constructor. """
if Singleton.__instance != None:
raise Exception("This class is a singleton!")
else:
Singleton.__instance = self
s = Singleton.getInstance()
print s
s = Singleton.getInstance()
print s
Decorator
Decorators are a very powerful and useful tool in Python since it allows
programmers to modify the behaviour of a function or class. Decorators allow us to
wrap another function in order to extend the behaviour of the wrapped function,
without permanently modifying it.
A decorator is the outer function that takes a function as an argument, defines a
wrapper function to modify it, and returns the wrapper.
Decorator is a structural pattern that allows adding new behaviors to objects
dynamically by placing them inside special wrapper objects, called decorators.
Decorator pattern allows a user to add new functionality to 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.
Decorator design pattern link:
https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_d
ecorator.htm
Observer pattern
You tube:InfoQ
• The Decorator design pattern attaches additional responsibilities to an
object dynamically.
• It is wrap up at another object. It will extend functionality of object
without affecting any other object.
• Decorators provide an alternative to subclassing for extending
functionality.
• Also known as Wrapper
Elements of Decorator Design
Pattern
Elements
• Component
• defines interface for objects that can have additional responsibilities added to them.
• ConcreteComponent
• defines an object on which additional responsibilities can be added
• Decorator
• maintains a reference to component object and defines an interface that conforms
to component's interface. In simple words, it has a component object to be
decorated.
• ConcreteDecorator
• add responsibilities to the component object.
Class Diagram for Decorator Design
Pattern
Example
Room(Component)
•It is an interface which creates a blue print for the class which will have decorators

SimpleRoom(ConcreteComponent)
•Object of SimpleRoom class will be decorated. Additional responsibilities will be attached to it
dynamically.

RoomDecorator(Decorator)
•It contains reference to Room class which will be decorated.

•ColorDecorator(ConcreteDecorator)
•ColorDecorator will add additional responsibility i.e., add color to room.

CurtainDecorator(ConcreteDecorator)
•CurtainDecorator will add additional responsibility i.e., add curtains to room.
Observer Design Pattern
• It is a behavioral design pattern where an object (known
as the subject) maintains a list of its dependents
(observers) and notifies them of state changes, typically
by calling one of their methods.
• Observer pattern is used when there is one-to-many
relationship between objects such as if one object is
modified, its dependent objects are to be notified
automatically.
Components of Observer Pattern
1. Subject
The subject maintains a list of observers (subscribers or listeners). It Provides methods to register and
unregister observers dynamically and defines a method to notify observers of changes in its state.
2. Observer
Observer defines an interface with an update method that concrete observers must implement and
ensures a common or consistent way for concrete observers to receive updates from the subject.
Concrete observers implement this interface, allowing them to react to changes in the subject’s state.
3.ConcreteSubject
ConcreteSubjects are specific implementations of the subject. They hold the actual state or data that
observers want to track. When this state changes, concrete subjects notify their observers.
For instance, if a weather station is the subject, specific weather stations in different locations would be
concrete subjects.
4. ConcreteObserver
Concrete Observer implements the observer interface. They register with a concrete subject and react
when notified of a state change. When the subject’s state changes, the concrete observer’s update()
method is invoked, allowing it to take appropriate actions.
Example: In a practical example, a weather app on your smartphone is a concrete observer that reacts
to changes from a weather station.
State Design Pattern
The State pattern allows an object to alter its behavior
when its internal state changes
Example
Imagine an e-commerce application where the behavior of
a shopping cart varies depending on whether it’s empty,
has items, or is in the process of checkout. Handling the
behavior transitions and business logic for each state
within a single class becomes unwieldy and leads to code
that is difficult to understand and maintain.
The State pattern allows us to encapsulate these states in
separate objects and switch between them
When to Use State Pattern
1.Dynamic State-Dependent Behavior: The State Pattern is ideal
when an object’s behavior depends on its state and must change at
runtime.
2.Eliminating Complex Conditional Statements: You should
consider using the State Pattern when you have multiple conditional
statements that switch an object’s behavior based on its state.
3.Seamless State Expansion: The State Pattern is beneficial when
you want to add new states to your system without altering existing
code
Key Components of the State Pattern
The State pattern is built around three main components:
4.Context: This class maintains a reference to the current state object
and delegates the state-specific behavior to it.
5.State: The State interface defines a set of methods that
encapsulate the behavior associated with a particular state.
3.Concrete States: These are the classes that
implement the State interface. Each concrete state
represents a specific state of the context and provides its
unique implementation of the state-specific behavior.
Class Diagram of Traffic Light
#Context Class
class TrafficLight:
def __init__(self): #Code Continued…
self.state = RedLight()
class GreenLight(LightState):
def change_state(self): def change(self, light):
self.state.change(self) print("Changing to Red.")
#State Class Interface
light.state = RedLight()
class LightState: traffic_light = TrafficLight()
def change(self, light): for i in range(3):
pass traffic_light.change_state()
class RedLight(LightState):
def change(self, light):
print("Changing to Yellow.")
light.state = YellowLight()
class YellowLight(LightState):
def change(self, light):
print("Changing to Green.")
light.state = GreenLight()
Template Design Pattern
The 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
Strategy Design Pattern
• The Strategy Design Pattern defines a family of algorithms,
encapsulates each one, and makes them interchangeable,
allowing clients to switch algorithms dynamically without
altering the code structure.
• It allows the behavior of an object to be selected at runtime.
1.Context
• The Context is a class or object that holds a reference to a strategy object
and delegates the task to it.
• It acts as the interface between the client and the strategy, providing a
unified way to execute the task without knowing the details of how it’s done.
• The Context maintains a reference to a strategy object and calls its methods
to perform the task, allowing for interchangeable strategies to be used.

2. Strategy Interface
• The Strategy Interface is an interface or abstract class that defines a set of
methods that all concrete strategies must implement.
• It serves as a contract, ensuring that all strategies adhere to the same set of
rules and can be used interchangeably by the Context.
• By defining a common interface, the Strategy Interface allows for decoupling
between the Context and the concrete strategies, promoting flexibility and
modularity in the design.
3. Concrete Strategies
• Concrete Strategies are the various implementations of the Strategy
Interface. Each concrete strategy provides a specific algorithm or
behavior for performing the task defined by the Strategy Interface.
• Concrete strategies encapsulate the details of their respective
algorithms and provide a method for executing the task.
• They are interchangeable and can be selected and configured by the
client based on the requirements of the task.

4. Client
• The Client is responsible for selecting and configuring the appropriate
strategy and providing it to the Context.
• It knows the requirements of the task and decides which strategy to use
based on those requirements.
• The client creates an instance of the desired concrete strategy and
passes it to the Context, enabling the Context to use the selected
strategy to perform the task.
Communication between the Components
In the Strategy Design Pattern, communication between
the components occurs in a structured and decoupled
manner. Here’s how the components interact with each
other:

Client to Context:
• The Client, which knows the requirements of the task,
interacts with the Context to initiate the task execution.
• The Client selects an appropriate strategy based on the task
requirements and provides it to the Context.
• The Client may configure the selected strategy before passing
it to the Context if necessary.
Context to Strategy:
• The Context holds a reference to the selected strategy and
delegates the task to it.
• The Context invokes a method on the strategy object, triggering
the execution of the specific algorithm or behavior encapsulated
within the strategy.
Strategy to Context:
• Once the strategy completes its execution, it may return a result or
perform any necessary actions.
• The strategy communicates the result or any relevant information
back to the Context, which may further process or utilize the result
as needed.
Strategy Interface as Contract:
• The Strategy Interface serves as a contract that defines a set of
methods that all concrete strategies must implement.
• The Context communicates with strategies through the common
interface, promoting interchangeability and decoupling.
Decoupled Communication

Communication between the components is decoupled, meaning that the


Context does not need to know the specific details of how each strategy implements the
task.
Strategies can be swapped or replaced without impacting the client or other
strategies, as long as they adhere to the common interface.
References
https://softwarepatterns.com/python

You might also like