In this video, discover how to use the Cloneable interface to implement the prototype pattern in Java. Learn how to create copies of objects, and find out the drawbacks of the Cloneable interface.
- [Instructor] The most common way to implement…the prototype pattern in Java is…with the Cloneable interface.…In this example there is a class called rabbit.…Rabbits have two characteristics,…an age in months and their breed.…There is an enum at the top of the class…that specifies the different types of breed…a rabbit could be, the class has methods…that sets and gets the age and the breed.…The purpose of the prototype pattern…is to be able to make exact copies…of a single rabbit object for example in the main class…a rabbit could be created and its age could be set…to two months and its breed to Himalayan.…
Then, if it is cloned, the new rabbit should have…the same age and the same breed as the original rabbit.…In order to do that the first thing to notice…about the rabbit class is that it implements…the Cloneable interface.…Secondly, the rabbit class needs to override…the clone method.…Inside the clone method a new rabbit is created…by calling super.clone.…The return type for the clone method is objects…so this should be cast to rabbits.…
Released
8/29/2018- What are creational design patterns?
- Avoid complex constructors
- Implementing the Builder pattern
- Multithreading with the Singleton pattern
- Using the Prototype pattern
- Implementing a simple Factory Method pattern
- Making code more flexible with the Abstract Factory pattern
Share this video
Embed this video
Video: Implement the Prototype pattern