The prototype design pattern is a creational pattern.
If the creation of an object is a very costly affair and we already have a similar kind of object, instead of creating it each time we need it, we use the clone of the object that is already there.
Suppose, there is a large object with many attributes whose data we read from a database. We need to modify that data multiple times in our program. So instead of creating the object each time by reading from the database, we tend to keep a prototype object - we clone it, and then work on it.
In Python, there is a module called copy which has two methods - copy() and deepcopy(). The first one is for the shallow copy and the second one is for the deepcopy.
Here is the source code of an example of the Prototype design pattern.
from abc import ABC, abstractmethod
import copy
class Person(ABC):
def __init__(self, name):
self._name = name
def set_name(self, name):
self._name = name
def get_name(self):
return self._name
@abstractmethod
def clone(self):
pass
@abstractmethod
def display(self):
pass
class Teacher(Person):
def __init__(self, name, course):
super().__init__(name)
self._course = course
def set_course(self, course):
self._course = course
def get_course(self):
return self._course
def display(self):
print("\nTeacher's name : ", self._name, "\n")
print("\nHe teaches : ", self.get_course())
def clone(self):
return copy.deepcopy(self)
class Student(Person):
def __init__(self, name, teacher):
super().__init__(name)
self._teacher = teacher
def display(self):
print("\n Student's name : ", self.get_name())
print("\n Taught by : ", self._teacher.get_name())
print("\n Enrolled in the subject : ", self._teacher.get_course())
def clone(self):
return copy.deepcopy(self)
if __name__ == '__main__':
teacher = Teacher('Som', "Python Design Patttern")
teacherClone1 = teacher.clone()
student = Student ("Ridit", teacherClone1)
studentClone1 = student.clone()
teacherClone1.set_course("DSA")
teacherClone1.display()
studentClone1.display()
If we run the above piece of code the result will be as follows:
Teacher's name : Som
He teaches : Python Design Patttern
Teacher's name : Som
He teaches : DSA
Student's name : Ridit
Taught by : Som
Enrolled in the subject : Python Design Patttern
As you can see, we have used deep copy here.
No comments:
Post a Comment