Creational Design Patterns: Prototype Pattern

The prototype pattern is used in order to create a copy of an object. This pattern can be really useful especially when creating an object from scratch is costly.
In comparison with the builder, factory and abstract factory patterns it does not create an object from scratch it clones/recreates it.
In comparison with the singleton pattern it creates multiple copies of an instance whilst the singleton has to ensure that only one will exist.

Imagine the scenario of an object, which in order to be created requires a very resource intensive method. It can be a database query with many joins or even the result of a Federated search.
We want those data to be processed by various algorithm using one thread per algorithm. Every thread should have its own copy of the original instance, since using the same object will result to inconsistent results.

So we have an interface for representing the result of a Search.

package com.gkatzioura.design.creational.prototype;

public interface SearchResult {

    SearchResult clone();

    int totalEntries();

    String getPage(int page);
}

And we have the implementation of the SearchResult the FederatedSearchResult.

package com.gkatzioura.design.creational.prototype;

import java.util.ArrayList;
import java.util.List;

public class FederatedSearchResult implements SearchResult {

    private List<String> pages = new ArrayList<String>();

    public FederatedSearchResult(List<String> pages) {
        this.pages = pages;
    }

    @Override
    public SearchResult clone() {

        final List<String> resultCopies = new ArrayList<String>();
        pages.forEach(p->resultCopies.add(p));
        FederatedSearchResult federatedSearchResult = new FederatedSearchResult(resultCopies);
        return federatedSearchResult;
    }

    @Override
    public int totalEntries() {
        return pages.size();
    }

    @Override
    public String getPage(int page) {
        return pages.get(page);
    }
}

So we can use the clone method and create as many copies as we need of a very expensive object to create.

You can find the sourcecode on github.

Also I have compiled a cheat sheet containing a summary of the Creational Design Patterns.
Sign up in the link to receive it.

2 thoughts on “Creational Design Patterns: Prototype Pattern

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.