Prototype Pattern

The prototype pattern is used when we want to reuse a lot of the attributes with the same values as on the to clone object. If the attributes used are coming from a database, we can prevent the call to a database for the attribute values by cloning the existing attributes.

Let’s take a look at a simple Example of a Cow class.

public class Cow implements Cloneable {
    private String name;
    private int number;
    private int weight;

    public Cow(String name, int number, int weight) {
        this.name = name;
        this.number = number;
        this.weight = weight;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Cow clone() {
        Cow clone = null;

        try {
            clone = (Cow) super.clone();

        } catch (CloneNotSupportedException e) {
           return null;
        }

        return  clone;
    }

    @Override
    public String toString() {
        return "Cow{" +
                "name='" + name + '\'' +
                ", number=" + number +
                ", weight=" + weight +
                '}';
    }
}

The catch inside the clone method will never be reached, so what we do doesn’t matter. Since I expect to clone a Cow I return a Cow type. A lot of the implementations I saw online returned an Object and started casting it to a Cow in the main. When cloning a Cow return a Cow this keeps the code more readable, because you get what you ask for.

Main

public static void main(String[] args) {
        Cow c = new Cow("cowy",1,350);
        Cow c1 = c.clone();

        System.out.println(c.hashCode());
        System.out.println(c1.hashCode());

        c1.setName("howdy");

        System.out.println(c);
        System.out.println(c1);
    }

Output

356573597
1735600054
Cow{name='cowy', number=1, weight=350}
Cow{name='howdy', number=1, weight=350}

As we can see the objects are different from each other. When we change one the other doesn’t change. This implementation of clone only works, because we use primitives (double) and Immutables (String). When an attribute is mutable we need to create a specific implementation for that part of the clone operation. A good example of that can be found here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s