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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay