Core Java

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.

Published on Java Code Geeks with permission by Emmanouil Gkatziouras, partner at our JCG program. See the original article here: Creational Design Patterns: Prototype Pattern

Opinions expressed by Java Code Geeks contributors are their own.

Emmanouil Gkatziouras

He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button