# Prototype

In 
Published 2022-12-03

This tutorial explains to you the design pattern named Prototype (which is a Creational Pattern).

# Prototype - theory

The Prototype pattern, is the way we can use to create copies/ clones of another objects. This is useful when the cost of creating an object is lower by cloning comparing with the standard case (when we might run a database query before or during the object instantiation).

Here it is the UML Diagram for Builder Pattern Example:

# Prototype - example

Here are the classes for showing how the Prototype Java Design Pattern works:

Prototype.java
public interface Prototype {
  public Prototype createClone();
}
Rabbit.java
public class Rabbit implements Prototype {
    
    private String name;
     
    public Rabbit(String name) {
        this.name = name;
    }
     
    public void setName(String name) {
        this.name = name;
    }
     
    public String getName() {
        return name;
    }
     
    @Override
    public Prototype createClone() {
        // TODO Auto-generated method stub
        return new Rabbit(name);
    }
}
Horse.java
public class Horse implements Prototype {


    private String name;
     
    public Horse(String name) {
        this.name = name;
    }
     
    public void setName(String name) {
        this.name = name;
    }
     
    public String getName() {
        return name;
    }
     
    @Override
    public Prototype createClone() {
        // TODO Auto-generated method stub
        return new Horse(name);
    }

}
Elephant.java
public class Elephant implements Prototype {

    private String name;
     
    public Elephant(String name) {
        this.name = name;
    }
     
    public void setName(String name) {
        this.name = name;
    }
     
    public String getName() {
        return name;
    }
     
    @Override
    public Prototype createClone() {
        // TODO Auto-generated method stub
        return new Elephant(name);
    }

}
PrototypeExampleMain.java
public class PrototypeExampleMain {
    public static void main(String[] args) {

        Rabbit rabbit1 = new Rabbit("Kili");
        Rabbit rabbit2 = (Rabbit) rabbit1.createClone();
         
        System.out.println("The 1st rabbit is named "+rabbit1.getName());
        System.out.println("The 2nd rabbit is named "+rabbit2.getName());     
    }
}

And here you have the example result :