How do I implement the Prototype pattern in Java?

Suppose an application creates monthly sales reports with the same initial sections. A configured report can serve as a template. Each month, the application copies it, changes the title, and adds the sections needed for that month.

Prototype is a Gang of Four creational pattern that creates objects by copying an existing instance. The prototype carries the configuration from which new objects are produced. A client can request a copy through an interface while the concrete class implements its copying rules. GoF pattern catalog

This article completes our creational patterns series following Factory Method, Abstract Factory, and Builder. The series began with Singleton.

A complete example

Save the following code as PrototypeExample.java. It uses standard Java APIs available in Java 8 and later.

package org.kodejava.pattern.prototype;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class PrototypeExample {
    interface Report {
        Report copy();
        void setTitle(String title);
        void addSection(String section);
    }

    static final class SalesReport implements Report {
        private String title;
        private final List<String> sections;

        SalesReport(String title, List<String> sections) {
            this.title = Objects.requireNonNull(title);
            this.sections = new ArrayList<>(sections);
        }

        private SalesReport(SalesReport original) {
            this(original.title, original.sections);
        }

        @Override
        public SalesReport copy() {
            return new SalesReport(this);
        }

        @Override
        public void setTitle(String title) {
            this.title = Objects.requireNonNull(title);
        }

        @Override
        public void addSection(String section) {
            sections.add(Objects.requireNonNull(section));
        }

        @Override
        public String toString() {
            return title + " " + sections;
        }
    }

    static Report customize(Report prototype) {
        Report report = prototype.copy();
        report.setTitle("November sales");
        report.addSection("Regional totals");
        return report;
    }

    public static void main(String[] args) {
        Report template = new SalesReport("Sales template",
                Arrays.asList("Summary", "Revenue"));
        Report november = customize(template);

        System.out.println("Template: " + template);
        System.out.println("Copy: " + november);
        System.out.println("Same instance: " + (template == november));

        november.addSection("Forecast");
        System.out.println("Template after edit: " + template);
        System.out.println("Copy after edit: " + november);
    }
}

Compile and run the example from the directory containing the source file.

javac -d out PrototypeExample.java
java -cp out org.kodejava.pattern.prototype.PrototypeExample

The program prints the original template and customized copy, then edits the copy again.

Template: Sales template [Summary, Revenue]
Copy: November sales [Summary, Revenue, Regional totals]
Same instance: false
Template after edit: Sales template [Summary, Revenue]
Copy after edit: November sales [Summary, Revenue, Regional totals, Forecast]

How copying works

GoF role Example Responsibility
Prototype Report Declares the copying operation used by the client.
Concrete prototype SalesReport Copies its title and sections according to its own rules.
Client customize() Obtains a copy through the interface and customizes it.
Configured prototype instance template in main() Supplies the initial report state.

The application creates the template once. The customize() method receives it through the Report interface and calls copy(). The concrete prototype returns a new SalesReport using a private copy constructor. Another report implementation could supply its own copying behavior through the same interface.

The false identity comparison shows that the template and copy are distinct report instances. Their section lists are also separate. The constructor creates a new ArrayList, so adding Regional totals or Forecast to the copy leaves the template’s sections intact.

The list elements are strings, which are immutable, so both lists can safely refer to the same section strings. If sections become mutable objects with their own fields, copying the list will still share those elements. The copy implementation must then decide which elements to duplicate and which references to share.

Choosing a copy policy

A useful copy contract states what the new object inherits and what becomes independent. In this example, the copy starts with the same title and section values, then owns its own mutable section list. A business object might also need a new identifier or a cleared creation timestamp.

Java provides Object.clone(), whose default behavior copies field values and shares referenced objects. This is a shallow copy. Our example exposes an explicit copy() method and constructs its result with the required list ownership. The Prototype pattern’s copying contract can be implemented this way. Object.clone() documentation

More elaborate object graphs require additional decisions. Shared subobjects, cycles, open resources, and external identities all affect what a valid copy means. Keep those decisions in the concrete prototype and document them for callers.

When should I use Prototype?

Prototype fits applications that repeatedly create objects from configured templates, particularly when client code works with multiple concrete types through a shared interface. A registry of named templates can let callers choose the starting configuration at runtime.

Copying also has a maintenance cost. When fields are added, review the copy operation so the new state receives the intended treatment. Copying large mutable graphs can consume substantial memory and time. Measure the actual construction and copying costs before choosing Prototype for performance.

For a small object with straightforward initialization, a constructor or factory can be sufficient. Prototype becomes useful when an existing instance provides the state needed to create another object.

Next, we begin structural patterns with Adapter.

How do I define bean scoping in Spring?

Bean scoping is how the bean is created and returned from the spring container to the bean requester. By default, the scope of all bean is singleton. The spring container will always return the same bean whenever this bean is required, for instance when in injected or call using the getBean() method from the application context.

There are five types of bean scope define in the Spring Container:

Scope Description
singleton Scope the bean definition to a single bean instance per Spring Container. This is the default scope when no scope is defined when creating a bean.
prototype Scope the bean to allow multiple times bean creation. This will create a new bean for each time the bean is required.
request Scope the bean definition to a single HTTP request. *
session Scope the bean definition to a single HTTP session. *
global-session Scope the bean definition to a global HTTP session. *

*) This is only valid when using the web-capable Spring context.

Let’s see the difference between Singleton and Prototype scope. First we’ll create our DummyService class.

package org.kodejava.spring.core;

public class DummyService {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Singleton Scope

By default, when no scope defined it will be a singleton.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="service" class="org.kodejava.spring.core.DummyService" />

</beans>

Now create a program to run our example. First will run it using the singleton.xml as the configuration.

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopeDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("singleton.xml")) {
            DummyService serviceA = (DummyService) context.getBean("service");
            serviceA.setMessage("Hello From A");
            System.out.println("Message A = " + serviceA.getMessage());

            DummyService serviceB = (DummyService) context.getBean("service");
            System.out.println("Message B = " + serviceB.getMessage());
        }
    }
}

The output of the singleton configuration is:

Message A = Hello From A
Message B = Hello From A

The above output show that the message printed by the serviceB is the same as the serviceA. We don’t even set the message in the serviceB explicitly. It prints the same message because the getBean() method actually return the same bean both for serviceA and serviceB. This is the singleton scope.

Prototype Scope

To change the scope to prototype use the scope attribute in the bean element as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="service" class="org.kodejava.spring.core.DummyService" scope="prototype" />

</beans>
package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopePrototypeDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("prototype.xml")) {
            DummyService serviceA = (DummyService) context.getBean("service");
            serviceA.setMessage("Hello From A");
            System.out.println("Message A = " + serviceA.getMessage());

            DummyService serviceB = (DummyService) context.getBean("service");
            System.out.println("Message B = " + serviceB.getMessage());
        }
    }
}

Now if you try to run the same program again but changing the configuration to prototype.xml you’ll get the following output printed:

Message A = Hello From A
Message B = null

The serviceB now print a different message. This is the effect of using the prototype scope. When we call the getBean() a new bean will be created per request.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central