BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent 18c6a1a0ab
commit 85e368d790
3 changed files with 14 additions and 8 deletions

View File

@@ -1,6 +1,6 @@
package com.baeldung.prototype;
public class Tree implements Cloneable {
public class Tree implements TreeCloneable {
private double mass;
private double height;
@@ -36,7 +36,12 @@ public class Tree implements Cloneable {
}
@Override
public Tree clone() {
public String toString() {
return "Tree [mass=" + mass + ", height=" + height + ", position=" + position + "]";
}
@Override
public TreeCloneable createA_Clone() {
Tree tree = null;
try {
tree = (Tree) super.clone();
@@ -46,9 +51,4 @@ public class Tree implements Cloneable {
return tree;
}
@Override
public String toString() {
return "Tree [mass=" + mass + ", height=" + height + ", position=" + position + "]";
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.prototype;
public interface TreeCloneable extends Cloneable {
TreeCloneable createA_Clone();
}

View File

@@ -15,7 +15,7 @@ public class TreePrototypeUnitTest {
Tree tree = new Tree(mass, height);
tree.setPosition(position);
Tree anotherTree = tree.clone();
Tree anotherTree = (Tree) tree.createA_Clone();
anotherTree.setPosition(otherPosition);
assertEquals(position, tree.getPosition());