Design Pattern Overview - Prototype
Prototype Pattern is a creational pattern to create new objects by cloning existed objects. Usually we use consutructor of class to create new instances, but you can also clone one from old object, then copy all the fields.
In what situation, we need use cloning to create new object? Can’t we just use constructors? Imagine you have an object, and you don’t know what class the object belongs to, how do you create another object of that class? Yes, you can clone one from the original object. Another possible place to apply prototype pattern is you want a new object but it’s very expensive to call the constructor. To clone one maybe a better solution.
When we use prototype pattern, we should define a
Prototype interface, whatever can be cloned must implement this
Prototype interface. In the client, we use
clone to get new instance of the concrete classes.
Look at the class diagrams above again, is the
Prototype interface very like
Object class in Java? Yes, the
Object use this pattern by default. But in Java
clone method is
protected, so yo can’t call it directly. What you need to do is extends
Object(every class must do that), override
clone method, and implements
Cloneable interface. The
Cloneable interface don’t have any method, it’s just a mark interface, indicating objects of the class which implements it can be cloned. If you didn’t implements this
Cloneable interface, a
CloneNotSupportedException wiil be thrown when you call