DEV Community

Erwan Le Tutour
Erwan Le Tutour

Posted on

Prototype design pattern — Java

design-pattern

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();
}
view raw Prototype.java hosted with ❤ by GitHub

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.

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay