In this video, discover how to implement the Prototype pattern when some of the fields are mutable values. Learn how to handle situations where non-primitive values are used.
- [Instructor] Problems can arise…with the Cloneable interface…when classes have fields that are mutable.…If the field types are primitive values like string or int,…there will probably not be any issues,…but if the field types are other classes,…there may be problems.…In this example, there is a class called Rabbit…and another class called Person.…The Person class has a field called Name,…and methods to get and set the name of the person.…The Rabbit class has fields for age and breed…and also a field called owner, which is of type Person.…
The SetOwner method in the Rabbit class…takes a parameter of type string…and creates a new Person object whose name is the string.…The Rabbit class also has a clone method…that creates a copy of the rabbit it is called on.…In the main class, a rabbit object is created.…The owner of the rabbit is set to a person called Sally…and then a second object called rabbitCopy is created,…which is a clone of the first rabbit.…It then prints out the names of the owners…of both the original rabbit and the cloned rabbit.…
- 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