Java Design Patterns – Prototype Pattern

The Prototype Pattern is using to create a new object instance by cloning the prototype object. This pattern is used to avoid new keyword.

In this post, you can find:

  • example situation when to use Prototype design pattern
  • Prototype pattern code structure in Java
  • example how to use Prototype pattern

Exemplary Situation

We have set of books. Books have attributes like e.g. name or description. We would want to have a class for each book. In this situation, we would have in the code a lot of new statements when we would want to create new objects of the book. The better idea is to have one class that will help to get an instance of book class.

Prototype pattern example in Java

Let’s create the interface of Book and a few books classes based on this interface. In the end, we would create PrototypeFactory class that would have HashMap with prototypes.

Interface Book

The most important method here is clone() that is the instance of Book.

Classes that implement Book interface

We implement Book interface method and writing the simple implementation. In clone() method we returning the new instance of the class.

PrototypeFactory

First, we create the static variable named prototypes and initialize new HashMap object on it. Next, in static we putting prototypes objects to Map. In the end, we create getPrototype() method that as the attribute would want the string with the name of book object to clone.

How to use Prototype pattern?

Look at the Client class:

Console output:

Prototype Pattern console output

Prototype pattern is simple to use. We create the variable with the instance of Book and via ProtorypeFactory we getting the proper instance of the class. At the very end, we use method info() on the variable to see the output from the console.

You can find the code used in this article on my GitHub: Prototype Pattern

Prototype Pattern is easy to learn and use. Look at your old code maybe you can find a good place to use this pattern. Your code would look and work much better. Write Prototype pattern on your own example. That’s the best way to learn.
Good luck!

Want more? Look at my others post about Design Patterns

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *