Changes the implementation of the prototype pattern #1103
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
In the code you use the copy constructor approach to implement (in contrast to the Java-cloning approach in the description). If you follow this approach, then in every non-abstract class
X
the clone method is defined asIn addition, every class (also the abstract base classes) must provide a copy constructor. I have added such constructors to the abstract base classes (which would allow to evolve these classes, i.e. to add private fields later on). These copy constructors are called form the sub classes.
The Cloneable interface does not need to be implemented, this interface is only needed when Java-Cloning is used, and the
CloneNotSupportedException
can also be dropped, as it is also only used in the context of Java Cloning (i.e. the mechanism provided by Object.clone, which is not used in this implmentation).As a consequence of the removal of the
CloneNotSupportedException
I also had to remove the testHeroFactoryImplTest.java
as this test checked this behavior. Actually the test was strange as it invoked clone on abstract classes which never can have instances.I also decided to change the abstract class
Prototype
into anInterface
.The contract of cloning states, that the returned object must be a new reference, but it must be equal to the origin. I added equals-implementations to all classes and added a line in the test to check whether the original and its copy are equal.