Over a million developers have joined DZone.

Creational Design Patterns: Prototype Pattern [Snippet]

DZone's Guide to

Creational Design Patterns: Prototype Pattern [Snippet]

Want to learn more about using creational design patterns? Check out this tutorial on how to use the prototype design pattern in Java to learn more!

· Java Zone ·
Free Resource

"I love writing authentication and authorization code." ~ No Developer Ever. Try Okta Instead.

The prototype pattern is used to create a copy of an object. This pattern can be really useful, especially when creating an object from scratch. In comparison with the builder, factory, and abstract factory patterns, it does not create an object from scratch — it clones it.
However, 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 that, 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 algorithms using one thread per algorithm. Every thread should have its own copy of the original instance, since using the same object will result in inconsistent results.

Here, 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 and 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;

    public SearchResult clone() {

        final List<String> resultCopies = new ArrayList<String>();
        FederatedSearchResult federatedSearchResult = new FederatedSearchResult(resultCopies);
        return federatedSearchResult;

    public int totalEntries() {
        return pages.size();

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

We can use the clone method and create as many copies as we need of this object.

You can find the source code on GitHub.

"I love writing authentication and authorization code." ~ No Developer Ever. Try Okta Instead.

java ,design-pattern ,creational design pattern ,snippet ,code ,singleton pattern ,prototype pattern

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}