DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Prototype Pattern in JavaScript
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Creating a Deep vs. Shallow Copy of an Object in Java

Trending

  • How To Compare DOCX Documents in Java
  • LLM Orchestrator: The Symphony of AI Services
  • Mastering Serverless Debugging
  • Efficient Data Management With Offset and Cursor-Based Pagination in Modern Applications
  1. DZone
  2. Coding
  3. Languages
  4. Prototype Pattern Tutorial with Java Examples

Prototype Pattern Tutorial with Java Examples

Learn the Prototype Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
Apr. 09, 10 · Tutorial
Like (14)
Save
Tweet
Share
89.6K Views

Join the DZone community and get the full member experience.

Join For Free

Today's pattern is the Prototype pattern which is utilized when creating an instance of a class is expensive or complicated.

Prototype in the Real World 

While the prototype that you first think of is a first draft of a new product, the prototype pattern is slightly different. The prototype pattern involves copying something that already exists. An example of this in the real world could be spliting a cell, where two identical cells are created. But let's not get too hung up on the real world - let's see the pattern in a software setting.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Prototype Pattern

The Prototype pattern is known as acreational pattern,as it is used to construct objects suchthaey they can be decoupled from their implementing systems. Thedefinition of Prototype as provided in the original Gang of Four book on DesignPatterns states: 

Create objects based on a template of an exsiting object through cloning.

In summary, instead of going to the trouble of creating object from scratch every time, you can make copies of an original instance and modify it as required.


The pattern is quite simple: the Prototype interface declares a method for cloning itself, while the ConcretePrototype implements the operation for cloning itself. 

In practice you will add in a registry to manage the finding and cloning of the objects. The detail of how it is used is best described in a code example.

When Would I Use This Pattern?

The Prototype pattern should be considered when

  • Composition, creation and representation of objects should be decoupled from the system
  • Classes to be created are specified at runtime
  • You need to hide the complexity of creating new instance from the client
  • Creating an object is an expensive operation and it would be more efficient to copy an object.
  • Objects are required that are similar to existing objects.

The pattern is used by the Clonable interface in Java. Cloneable is implemented as a marker interface to show what objects can be cloned, as Object already defined a protected clone() method. Client can override, or call the superclass implementation, of this clone method to do the copy.


So How Does It Work In Java?

Let's use a simple example in Java to illustrate this pattern. For this example, let's use a shopping cart example. Let's say that we have a number of items that can go in the cart - books, cds, dvds. While our example doesn't include anything that's particularly expensive to create, it should illustrate how the pattern works.

First, we'll create an abstract class for our Item, which will be our Prototype that includes a clone method. 

//Prototypepublic abstract class Item{   private String title;   private double price;     public Item clone()   {      Item clonedItem = null;     try {               //use default object clone.            clonedItem = (Item) super.clone();             //specialised clone            clonedItem .setPrice(price);             clonedItem.setTitle(title);      } catch (CloneNotSupportedException e) {          e.printStackTrace();          } // catch     return clonedItem ;   }    public String getTitle()   { return title; }    public double getPrice()   {  return price;}}

Next we'll create two ConcretePrototypes

//Concrete Prototypespublic class Book extends Item{  //extra book stuff }public class CD extends Item{  //extra cd stuff}

Now let's create a registry for item creation 

public class ItemRegistry{private Hashtable map  = new Hashtable();     public ItemRegistry{   loadCache();}    public Item createBasicItem(String type) {    return map.get(type).clone();   }    private void loadCache()    {    Book book = new Book();book.setTitle("Design Patterns"); book.setPrice(20.00);map.add("Book", book); CD cd = new CD();cd.setTitle("Various"); cd.setPrice(10.00);map.add("CD", cd);     }}

 

 

Finally, here's a Client that makes use of the Prototype. If we need to create a book, we can use the cached implementation to load it up, and modify it after.

public class Client{   public static void main(String[] args)   {      ItemRegistry registry = new ItemRegistry();      Book myBook = registry.createBasicItem("Book");       myBook.setTitle("Custom Title");       //etc   }}

 


Watch Out for the Downsides

One of the downsides to this pattern is that the process of copying an object can be complicated. Also, classes that have circular references to other classes are difficult to clone. Overuse of the pattern could affect performance, as the prototype object itself would need to be instantiated if you use a registry of prototypes. 

Next Up

We're going to look at the Memento pattern next week.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern
Prototype pattern Prototype Java (programming language) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Prototype Pattern in JavaScript
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Creating a Deep vs. Shallow Copy of an Object in Java

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: