Tutorial

Prototype Design Pattern in Java

Published on August 3, 2022
author

Pankaj

Prototype Design Pattern in Java

Prototype design pattern is one of the Creational Design pattern, so it provides a mechanism of object creation.

Prototype Design Pattern

prototype design pattern Prototype design pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. Prototype pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. Prototype design pattern uses java cloning to copy the object.

Prototype Design Pattern Example

It would be easy to understand prototype design pattern with an example. Suppose we have an Object that loads data from database. Now we need to modify this data in our program multiple times, so it’s not a good idea to create the Object using new keyword and load all the data again from database. The better approach would be to clone the existing object into a new object and then do the data manipulation. Prototype design pattern mandates that the Object which you are copying should provide the copying feature. It should not be done by any other class. However whether to use shallow or deep copy of the Object properties depends on the requirements and its a design decision. Here is a sample program showing Prototype design pattern example in java. Employees.java

package com.journaldev.design.prototype;

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

public class Employees implements Cloneable{

	private List<String> empList;
	
	public Employees(){
		empList = new ArrayList<String>();
	}
	
	public Employees(List<String> list){
		this.empList=list;
	}
	public void loadData(){
		//read all employees from database and put into the list
		empList.add("Pankaj");
		empList.add("Raj");
		empList.add("David");
		empList.add("Lisa");
	}
	
	public List<String> getEmpList() {
		return empList;
	}

	@Override
	public Object clone() throws CloneNotSupportedException{
			List<String> temp = new ArrayList<String>();
			for(String s : this.getEmpList()){
				temp.add(s);
			}
			return new Employees(temp);
	}
	
}

Notice that the clone method is overridden to provide a deep copy of the employees list. Here is the prototype design pattern example test program that will show the benefit of prototype pattern. PrototypePatternTest.java

package com.journaldev.design.test;

import java.util.List;

import com.journaldev.design.prototype.Employees;

public class PrototypePatternTest {

	public static void main(String[] args) throws CloneNotSupportedException {
		Employees emps = new Employees();
		emps.loadData();
		
		//Use the clone method to get the Employee object
		Employees empsNew = (Employees) emps.clone();
		Employees empsNew1 = (Employees) emps.clone();
		List<String> list = empsNew.getEmpList();
		list.add("John");
		List<String> list1 = empsNew1.getEmpList();
		list1.remove("Pankaj");
		
		System.out.println("emps List: "+emps.getEmpList());
		System.out.println("empsNew List: "+list);
		System.out.println("empsNew1 List: "+list1);
	}

}

Output of the above prototype design pattern example program is:

emps List: [Pankaj, Raj, David, Lisa]
empsNew List: [Pankaj, Raj, David, Lisa, John]
empsNew1 List: [Raj, David, Lisa]

If the object cloning was not provided, we will have to make database call to fetch the employee list every time. Then do the manipulations that would have been resource and time consuming. That’s all for prototype design pattern in java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 22, 2014

Hi Pankaj, Nice explaination. One correction, it is written as ‘Notice that the clone method is overridden to provide a deep copy of the employees list.’ But clone method created shallow copy and not deep copy.

- Amit N

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 24, 2014

Hi, By default clone method created shallow copy but here we want deep copy. We have to provide the definition for deep copy in clone method by our self.

- kaushal

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 17, 2014

    Program says List… but it is printing as hashmap… how it is possible? System.out.println("emps List: "+emps.getEmpList()); System.out.println("empsNew List: "+list); System.out.println("empsNew1 List: "+list1

    - Vinod

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 14, 2015

      Your tutorials arereally wonderful and easy to understand.I was wondering where can we use prototype pattern in real time.

      - Supriya

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 27, 2015

        what would happen if I would add one employee(“John”) in the list (list) and save it to the database, and from (list1) i want to remove the “John” but it would say it does not exist? can you please elaborate more onhere can we use this

        - Kunal Bansal

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 13, 2017

        Hi Kunal, I feel - addition/removal of employees and saving into database are not real objective here. This is just for an example. The main objective of prototype design is - we can use the clone of an existing object instead of creating a new one. Now what you will do with this objects (original and clone) depends on your requirements.

        - DEBARATI MAJUMDER

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 13, 2016

          Hi Pankaj, i can very well call the below 2 lines of code with creating a new object /calling a db emps.getEmpList().add(“John”); emps.getEmpList().remove(“Pankaj”); I havent understood the exact thing… can u please explain.

          - Sashi

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 13, 2016

          sry it is without creating a new object**

          - Sashi

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 28, 2016

            I got a doubt after implementing this design pattern. When I update database using changed list lets say List list = empsNew.getEmpList(); list.add(“John”); whith this list and I will get list1 like List list1 = empsNew1.getEmpList(); then I will get old list. So isn’t it have data inconsistency issue?

            - Sandeep

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              December 13, 2016

              what is use of implementing Cloneable interface in this example and suppose i removed cloneable interface then what will happened.it will clone object,i tried to remove cloneable interface but same output came,please explain

              - salil

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 28, 2017

              If you look at the javadoc of Cloneable, it states that Invoking Object’s clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown. In the above example, clone() method was overridden to show Deep copy(here new ArrayList is created) Removing of Cloneable interface did not impacted your code because, clone() method worked as normal method. But if you comment the clone() method from Employees class and try to use Object’s clone() method, it will throw exception.

              - sharad chandra

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                December 20, 2016

                Dear Pankaj, I was experimenting with the code you provided here. Found something really weird that I couldn’t understand. Please check the following method. @Override public Object clone() throws CloneNotSupportedException { return new PlayersList(empList); } Instead of returning the ‘temp’ ArrayList, I returned the ‘empList’. output like this: emps HashMap : [Pankaj, Raj, David, Lisa] empsNew HashMap : [Raj, David, Lisa, John] empsNew1 HashMap : [Raj, David, Lisa, John] I think there is something that I have failed to understand. An explanation would be of great help. Thanks a lot for these nice, useful and easy to implement tutorials.

                - Tahmid

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                December 20, 2016

                Just got the answer. . . The clone generally shares state with the object being cloned. If that state is mutable, you don’t have two independent objects. If you modify one, the other changes as well. And all of a sudden, you get random behavior. - Josh Bloch

                - Tahmid

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  September 26, 2017

                  Thanks, very nice expl

                  - Arun SIngh

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    September 27, 2017

                    Hi Pankaj, Could you please provide JDK example as well for prototype design pattern?

                    - Ganesh AC

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 12, 2017

                      Thanks! Very useful

                      - Amine KOUIS

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        June 8, 2018

                        The Clone method still use new to correct object. it does not meet the design pattern requirement. “Prototype design pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing.” It do save time to get data from DB. Is below clone method better? @Override protected Object clone() throws CloneNotSupportedException { Object ee = (Employees)super.clone(); List tmp = new ArrayList(); ((Employees) ee).setEmpList(tmp); for(String s: this.empList) tmp.add(s); return ee; }

                        - Ying Zhang

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          January 16, 2019

                          Hi, You mentioned that creating an object using a new operator is costly. But in your code you are still using new method to deep clone the object. Then what is the difference between the traditional way of creation and creation using prototype? Thanks

                          - Thejus Singh Jagadish

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            January 20, 2019

                            Hi, Why do you implement Cloneable interface and override clone method? You are using new operator which will give you a new memory address where you copy all the elements from the old structure. Do we relly need to implement this interface in this case?

                            - Adrian

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              April 15, 2019

                              Very useful example of the prototype to help my understanding While not Java, I have created a video tutorial of the Protoype pattern in python that is getting a good response. https://youtu.be/\_jBjhI6-VDI

                              - SeanWasere YTBE

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                February 1, 2020

                                Beautiful and easy to understand !, thanks

                                - Ajay

                                  Try DigitalOcean for free

                                  Click below to sign up and get $200 of credit to try our products over 60 days!

                                  Sign up

                                  Join the Tech Talk
                                  Success! Thank you! Please check your email for further details.

                                  Please complete your information!

                                  Become a contributor for community

                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                  DigitalOcean Documentation

                                  Full documentation for every DigitalOcean product.

                                  Resources for startups and SMBs

                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                  Get our newsletter

                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                  The developer cloud

                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                  Get started for free

                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                  *This promotional offer applies to new accounts only.