Prototype Pattern
What is Prototype?
Prototype pattern is a creational design pattern. The prototype pattern is used when creating an object from a class is very costly for example, calling the database each time reduce performance and is very time-consuming. It is better to cache the object, returns its copy (Clone).
Why Prototype?
Prototype create a duplicate of an object which can be used as an instance of an object for creating other similar objects. It keeps performance while object creating as directly is costly. Cache objects return its clone on the next request.
Person obj1 = new Person();
Person obj2 = new Person();
obj1.Name = “Mahsa”;
obj2 = obj1;
obj2.Name = “Sara”;
return obj1.Name; => “Sara” => obj1 = obj2 => It is not what we want
When to use Prototype?
Examples:
There is a book class and on the client, we want to get its clone by using this.MemberwiseClone() which implement shallow copy.
How to use Prototype?
Prototype C# Code
Main Class C#
public class Book
{
public string Name = "";
public Book getClone()
{
Book obj;
obj = (Book) this.MemberwiseClone();
return obj;
}
}
Client C#
static void Main(string[] args)
{
Book obj1 = new Book();
obj1.Name = "Mahsa";
Book obj2;
obj2 = obj1.getClone();
}
Prototype Java Code
Main Class Java
public class Book
{
public string Name = "";
public Book getClone()
{
Book obj;
obj = (Book) this.MemberwiseClone();
return obj;
}
}
Client Java
static void Main(string[] args)
{
Book obj1 = new Book();
obj1.Name = "Mahsa";
Book obj2;
obj2 = obj1.getClone();
}
Prototype Python Code
Main Class Python
class Book(object):
def __init__(self):
self._name = "Mahsa"
Client Python
import copy
def main():
#Shallow Copy shallow_b1 = Book()
shallow_b2 = shallow_b1 shallow_b2._name="Sara"
print("shallow_b1: ", shallow_b1._name)
print("shallow_b2: ", shallow_b2._name) #Deep Copy
deep_b1 = Book()
deep_b2 = copy.deepcopy(deep_b1) deep_b2._name="Sara"
print("deep_b1: ",deep_b1._name)
print("deep_b2: ",deep_b2._name)if __name__ == "__main__":
main()