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.
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.
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.
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.
- 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.
- Hides complexities of creating of objects.
- The clients can get new objects without knowing whose type it will be.
- Reduce subclassing.
- 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:
Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code
Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!
To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.