Core Java

Prototype Design Pattern: Creating another dolly

It’s really a time consuming process to create objects and also an expensive affair. So we are now on a venture to save both time and money. How do we do that?

Cloning wonder Dolly

Anybody remember about Dolly? Yes, it’s the sheep which was the first mammal to be cloned. Well I don’t want to dig into the details but the key point is it’s all about cloning. It’s about creating a duplicate.

Prototype Design Pattern is pretty much similar to this real life example. This is another in the series of Creational Design Pattern part of the Gang of Four Design Pattern.

So this pattern works by cloning of an object rather than creation unlike Factory patterns.

When to use this pattern?

  • If the cost of creating the object is expensive or complicated.
  • When trying to keep the number of classes in an application to a minimum
  • When adding or removing objects at runtime
  • When the client application needs to be unaware of the object creation, composition and representation.
  • Objects are required which are similar to the existing objects

What does Prototype pattern do?

Prototype pattern allows making new instances by copying the existing instances. Prototype pattern results in a cloned object which is different from the original object. The state of the original is the same as the clone, at the time of cloning. Thereafter each object may undergo state change. We can modify the objects to perform different things as well. The only good thing is client can make new instances without knowing which specific class is being instantiated.

Structure:

The prototype class declares an interface for cloning itself by implementing the Cloneable interface and using the clone() method. Concrete Prototype implements the clone() method for cloning itself. And the client class creates a new object by asking Prototype to clone itself rather than using the new keyword.

Prototype Pattern Structure

The flow of events works in such a manner that the original class (e.g. Class A) is already initialized and instantiated. This is because we cannot use the clone as it is. We need to instantiate the original class (Class A) before using it. The client then requests the Prototype class for a new object of the same type as Class A. A concrete prototype depending on the type of object needed provides the object by cloning itself using the clone() method.

Imagine a scenario where there might be requirements where we have to get the user profile data from the backend for multiple processing e.g. user profile or roles etc which does not get changed very frequently. So we might have to use expensive database resources, connections and transactions. In this case we can store the data in single call and cache it in the session for further processing.

In the above example UserProfile object is the main object which will be cloned. The UserProfile implements the Cloneable interface. The BankDetails and Identity classes inherit from the UserProfile class. These are the concrete prototype classes.

We have introduced a new class called UserProfileRegistry which finds appropriate UserProfile instance and then returns the clone to the client class appropriately.

Prototype Pattern Example

You would need to clone() an Object when you want to create another Object at runtime that is a true copy of the Object you are cloning. True copy means all the attributes of the newly created Object should be the same as the Object you are cloning. If you could have instantiated the class by using new instead, you would get an Object with all attributes as their initial values. For example, if you are designing a system for performing bank account transactions, then you would want to make a copy of the Object that holds your account information, perform transactions on it, and then replace the original Object with the modified one. In such cases, you would want to use clone() instead of new.
 
Interesting points:

  • The Creational Design pattern can co-exist together e.g. Abstract factory, Builder and Prototype can use Singleton Pattern during their implementation or they might also work in isolation.
  • Prototype pattern definitely need initialize operation but don’t need sub classing but Factory Method requires subclassing but don’t require initialize operation.
  • Beneficial in Bank based transaction where we have expensive database queries. Caching might help and prototype pattern is the best answer to this situation as copy of the object having bank account information or user profile information can be used , perform transaction on it and then replace the original object with the modified one.
  • The above example uses Shallow cloning method. However we can implement through deep cloning as well. A detailed explanation on this topic can be found in our article: Deep diving into Cloning.

Benefits:

  • Hides complexities of creating of objects.
  • The clients can get new objects without knowing whose type it will be.
  • Reduce subclassing.

Drawback:

  • Drawback to using the Prototype is that making a copy of an object can sometimes be complicated.
  • Classes that have circular references to other classes cannot really be cloned.

Download Source Code:


 

Reference: Prototype Design Pattern: Creating another dolly from our JCG partner Mainak Goswami at the Idiotechie blog.

Mainak Goswami

Mainak Goswami is an experienced Technology Consultant specializing in JEE, Web Development and Open source technologies. He is currently based out of United Kingdom. He is a technology enthusiast trying to explore the latest in the world of technology. His current area of interest is Mobility, NoSQL and Cloud computing. In past time he loves blogging on his website Idiotechie.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button