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
package main.prototype; | |
public interface Prototype { | |
public Prototype getClone(); | |
} |
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.
package main.prototype; | |
public class Human implements Prototype{ | |
private String name; | |
private String lastName; | |
private int age; | |
public Human(){ | |
System.out.println(" Human description "); | |
System.out.println("---------------------------------"); | |
System.out.println("Name"+"\t"+"Last Name"+"\t"+"Age"); | |
} | |
public Human(String name, String lastName, int age) { | |
this(); | |
this.name = name; | |
this.lastName = lastName; | |
this.age = age; | |
showHuman(); | |
} | |
private void showHuman(){ | |
System.out.println(name+"\t"+lastName+"\t"+age); | |
} | |
@Override | |
public Prototype getClone() { | |
return new Human(name, lastName, age); | |
} | |
} |
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
package main.prototype; | |
public class HumanPrototypeMain extends Human { | |
public static void main(String[] args) { | |
Human human1 = new Human("Erwan", "Le Tutour", 30); | |
Human human2 = (Human) human1.getClone(); | |
} | |
} |
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.
Top comments (0)