From the course: Java Design Patterns: Creational
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Implement the Prototype pattern - Java Tutorial
From the course: Java Design Patterns: Creational
Implement the Prototype pattern
- [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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.