Prototype design pattern — Java
Prototype design pattern tutorial
Definition of Prototype pattern
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
Where to use the Prototype pattern
If the cost for creating a new object is expensive and costs resources.
UML example of the Prototype pattern
Implementation of the builder pattern
First we need to create our prototype class
The getClone() method will be implemented in the class that will implement the prototype to return a new object of the same class.
In the next example we will create a Human and then implement the method to clone him.
As you can read, the getClone() will return me another Human with the same name, last name and age to the one created before.
Exemple :
The following code will give me the following output
Human description
---------------------------------
Name Last Name Age
Erwan Le Tutour 30
Human description
---------------------------------
Name Last Name Age
Erwan Le Tutour 30
As you can see above, my human2 has the same properties values as my human1, but they will only be equals if I implement the equals() method to do so.