Over a million developers have joined DZone.
Platinum Partner

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

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

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

Structural Patterns

Behavioral Patterns

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

java,patterns,design patterns,design patterns uncovered

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

{{ parent.tldr }}

{{ parent.urlSource.name }}