Skip to content

Changes the implementation of the prototype pattern #1103

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 19, 2019
Merged

Changes the implementation of the prototype pattern #1103

merged 3 commits into from
Nov 19, 2019

Conversation

dgruntz
Copy link
Contributor

@dgruntz dgruntz commented Nov 18, 2019

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 as

public X clone() { return new X(this); }

In 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 test HeroFactoryImplTest.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 an Interface.

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.

@iluwatar iluwatar self-assigned this Nov 19, 2019
@iluwatar iluwatar added this to the 1.23.0 milestone Nov 19, 2019
@iluwatar iluwatar merged commit 515b7e7 into iluwatar:master Nov 19, 2019
@iluwatar
Copy link
Owner

@dgruntz many thanks for the improvements! 👍

@dgruntz dgruntz deleted the clone-impl branch November 19, 2019 13:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants