KEMBAR78
Sda Report | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
25 views13 pages

Sda Report

Uploaded by

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

Sda Report

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE

SOFTWARE DESIGN ARCHITECTURE

CSE 203

REPORT

TOPIC NAME : PROTOTYPE DESIGN PATTERN

GROUP MEMBERS:

➢ SHAHROZ KASHIF
➢ RUBA SYED
➢ ABHIA SULTANA
➢ MUHAMMAD HASSAM BIN ZAHID
Overview:
This presentation introduces the Prototype Design Pattern in Python, allowing for
efficient object creation by copying existing ones. Through code examples, it
showcases the pattern's implementation using abstract base classes and the `copy`
module. Attendees will gain insights into the benefits and practical applications of
the Prototype Pattern in Python development.

Introduction:
The Prototype Design Pattern is a creational design pattern used in software
development to create new objects by cloning existing ones. This pattern is
particularly effective in situations where the creation of a new instance of a class is
expensive or complex. By using a prototype, a new object can be created by
copying an existing object, thereby reducing the overhead associated with object
creation.

Problem Statement:
Inefficient object creation processes hinder software scalability and
maintainability. The absence of a flexible mechanism for dynamic object creation
poses challenges in adapting to changing requirements. This presentation addresses
these issues by introducing the Prototype Design Pattern in Python, aiming to
streamline object creation through efficient cloning of existing objects.

Key Concepts:
Prototype: An original object that is used as a template for creating new objects.
Cloning: The process of creating a new object by copying an existing object.
Deep Copy vs. Shallow Copy: A deep copy involves duplicating all objects
referenced by the original object, whereas a shallow copy involves duplicating
only the top-level object and referencing the original nested objects.

Objectives:

The main objectives of using the Prototype Design Pattern include:


Efficiency: Reduce the cost and complexity of object creation by cloning existing
prototypes.

Flexibility: Enable dynamic and flexible creation of objects at runtime based on


varying requirements.

Reusability: Promote the reuse of existing objects by cloning them, avoiding the
need for repetitive initialization logic.

Simplification: Simplify the creation of complex objects by using prototypes as


templates.

Components of the Prototype Design Pattern:

1. Prototype Interface or Abstract Class

Role: Provides a blueprint for creating new objects by defining the cloning
contract.
Purpose: Ensures all prototypes can be cloned consistently.
Key Method: Declares the clone method which concrete prototypes must
implement.

2. Concrete Prototype

Role: Represents a specific type of object to be cloned.


Purpose: Implements the clone method with the logic specific to the class.
Key Method: Defines how the cloning process should be carried out for instances
of the class.

3. Client

Role: Requests the creation of new objects by interacting with the prototype.
Purpose: Initiates the cloning process without needing to know the details of the
concrete classes involved.
Function: Uses the clone method to create new instances based on the prototype.

4. Clone Method

Role: Declared in the prototype interface or abstract class.


Purpose: Specifies how an object should be copied or cloned.
Function: Concrete prototypes implement this method to define their unique
cloning behavior, ensuring the object's internal state is duplicated to create a new,
independent instance.

UML Diagram of Prototype Design Pattern


UML Example demonstrating the Prototype Design Pattern:

Code of Above Diagram:

import copy
from abc import ABC, abstractmethod

# Prototype Interface
class Shape(ABC):
@abstractmethod
def clone(self):
pass

@abstractmethod
def draw(self):
pass

# Concrete Prototype
class Circle(Shape):
def __init__(self, color):
self.color = color

def clone(self):
return copy.deepcopy(self)

def draw(self):
print(f"Drawing a circle with color {self.color}")

# Client
class ShapeClient:
def __init__(self, shape_prototype):
self.shape_prototype = shape_prototype

def create_shape(self):
return self.shape_prototype.clone()

# Main
class PrototypeExample:
@staticmethod
def main(args):
# Create a prototype
circle_prototype = Circle("Red")

# Create a client with the prototype


shape_client = ShapeClient(circle_prototype)
# Use the client to create new shapes
new_circle = shape_client.create_shape()
new_circle.draw() # Output: Drawing a circle with color Red

if __name__ == "__main__":
PrototypeExample.main([])

How it Works

Prototype Interface

1. Shape Interface:

 This is an abstract base class (ABC) that defines the interface for the
prototype objects.
 It declares two abstract methods: clone and draw, which must be
implemented by any concrete prototype class.
 The clone method is responsible for creating a copy of the object.
 The draw method is intended to be used for rendering or displaying the
object.

Concrete Prototype

2. Circle Class:

 This class is a concrete implementation of the Shape interface.


 The constructor (__init__) initializes the color attribute of the circle.
 The clone method uses the copy.deepcopy function to create and return a
deep copy of the current instance.

 Deep copying ensures that all nested objects are also copied, not just the
references.

 The draw method provides a specific implementation to print out the circle's
color.
Client

3. ShapeClient Class:

 This class acts as a client that uses the prototype to create new instances.
 It holds a reference to a shape_prototype, which is an instance of a Shape (or
its subclass).
 The create_shape method clones the stored prototype, producing a new
instance of the same type.

Main

4. PrototypeExample Class:

 This class contains the main method, which serves as the entry point for the
program.
 Inside the main method:

 A Circle instance (circle_prototype) with the color "Red" is created.


 A ShapeClient instance (shape_client) is created, taking the circle_prototype
as its prototype.
 The client (shape_client) uses the create_shape method to clone the
circle_prototype, producing a new circle instance.
 The new circle's draw method is called, which outputs: Drawing a circle
with color Red.

When to Use Prototype Design Pattern


The Prototype Design Pattern is useful when you need to create new objects by
cloning existing objects, rather than creating them from scratch. This pattern is
particularly beneficial in the following scenarios:

1. Object Creation Efficiency:

 Allows objects to be created by copying existing prototypes, minimizing the


overhead associated with costly instantiation processes.
 Cloning existing instances is more efficient than creating new instances from
scratch, especially in scenarios where object creation is resource-intensive.
2. Reducing Overhead:

 Helps in scenarios where objects require complex setups or costly


initialization routines.
 By using prototypes, the overhead of repeating setup for each new instance
is reduced, as the prototype serves as a blueprint that can be customized as
needed.

3. Dynamic Object Creation:

 Enables the creation of new objects dynamically at runtime based on


changing conditions or user input.
 Different variations of an object can be cloned from existing prototypes,
providing flexibility and adaptability in dynamic environments.

4. Avoiding Subclass Explosion:

 Addresses situations where managing a large number of subclasses becomes


unwieldy.
 Abstracts the creation process, allowing new objects to be created without
explicitly referring to individual subclasses, thus keeping the codebase clean
and manageable.

In summary, the Prototype Design Pattern offers solutions to various challenges


related to object creation efficiency, overhead reduction, dynamic object creation,
and managing subclass proliferation, making it a valuable tool in software design
and architecture.

2nd Example:
Code:

from enum import Enum


from copy import deepcopy

class PersonType(Enum):
STUDENT = 1
EMPLOYEE = 2

class Person:
def __init__(self, NIC="", Name="", Dob=""):
self.NIC = NIC
self.Name = Name
self.Dob = Dob

def __str__(self):
return f"{self.__class__.__name__}{{NIC={self.NIC}, Name={self.Name},
Dob={self.Dob}}}"

class Student(Person):
def __init__(self, NIC="", Name="", Dob="", StudentID=""):
super().__init__(NIC, Name, Dob)
self.StudentID = StudentID

def __str__(self):
return f"{super().__str__()}, StudentID={self.StudentID}"

class Employee(Person):
def __init__(self, NIC="", Name="", Dob="", EmployeeID="", Salary=0.0):
super().__init__(NIC, Name, Dob)
self.EmployeeID = EmployeeID
self.Salary = Salary

def __str__(self):
return f"{super().__str__()}, EmployeeID={self.EmployeeID},
Salary={self.Salary}"

class PersonRegistry:
def __init__(self):
self.persons = {}
self.initialize()

def getPerson(self, personType):


return deepcopy(self.persons.get(personType))

def initialize(self):
employee = Employee("693629377V", "Nimali Perera", "1969.05.29",
"M2392", 60000.00)
student = Student("974535211V", "Meraki Bandara", "1997.08.19",
"IT19273826")
self.persons.update({
PersonType.EMPLOYEE: employee,
PersonType.STUDENT: student
})

if __name__ == "__main__":
personRegistry = PersonRegistry()
employee = personRegistry.getPerson(PersonType.EMPLOYEE)
print(employee)

employee.Salary = 70000.00
print(employee)

employee1 = personRegistry.getPerson(PersonType.EMPLOYEE)
print(employee1)

Advantages:
 Reduces the need for subclassing: Instead of creating a large hierarchy of
subclasses, objects can be cloned and modified.
 Performance: Cloning is usually more efficient than instantiation,
especially when the objects involved are complex.
 Runtime flexibility: New types of objects can be created at runtime by
cloning prototypes.

Disadvantages:
 Deep Copy Issues: Cloning can be complex if the objects have circular
references or other intricate structures.
 Cloning Overhead: Implementing a proper clone method might require
additional resources and careful handling of object states.

Conclusion:
The Prototype Design Pattern is a powerful tool in software development, allowing
for efficient and flexible object creation by cloning existing objects. It reduces the
need for complex instantiation logic and can improve performance in systems
where object creation is costly. However, careful implementation is necessary to
handle cloning complexities, especially with deep copies and state management.

By leveraging the Prototype Design Pattern, developers can create more efficient,
flexible, and maintainable software systems. It allows for the reuse of existing
object configurations, streamlines the creation of complex objects, and adapts
dynamically to changing requirements. When implemented thoughtfully, the
Prototype Design Pattern can significantly enhance the performance and
maintainability of software applications.

You might also like