BAEL-3091: The Prototype Pattern in Java (further changes based on suggestions)
This commit is contained in:
parent
aafe3d90df
commit
240c9fa3c4
@ -15,7 +15,9 @@ public class PineTree extends Tree {
|
||||
|
||||
@Override
|
||||
public Tree copy() {
|
||||
return new PineTree(this.getMass(), this.getHeight());
|
||||
PineTree pineTreeClone = new PineTree(this.getMass(), this.getHeight());
|
||||
pineTreeClone.setPosition(this.getPosition());
|
||||
return pineTreeClone;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -8,14 +8,16 @@ public class PlasticTree extends Tree {
|
||||
super(mass, height);
|
||||
this.name = "PlasticTree";
|
||||
}
|
||||
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tree copy() {
|
||||
return new PlasticTree(this.getMass(), this.getHeight());
|
||||
PlasticTree plasticTreeClone = new PlasticTree(this.getMass(), this.getHeight());
|
||||
plasticTreeClone.setPosition(this.getPosition());
|
||||
return plasticTreeClone;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -2,6 +2,10 @@ package com.baeldung.prototype;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class TreePrototypeUnitTest {
|
||||
@ -38,4 +42,27 @@ public class TreePrototypeUnitTest {
|
||||
assertEquals(position, pineTree.getPosition());
|
||||
assertEquals(otherPosition, anotherPineTree.getPosition());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenA_ListOfTreesWhenClonedThenCreateListOfClones() {
|
||||
double mass = 10.0;
|
||||
double height = 3.7;
|
||||
Position position = new Position(3, 7);
|
||||
Position otherPosition = new Position(4, 8);
|
||||
|
||||
PlasticTree plasticTree = new PlasticTree(mass, height);
|
||||
plasticTree.setPosition(position);
|
||||
PineTree pineTree = new PineTree(mass, height);
|
||||
pineTree.setPosition(otherPosition);
|
||||
|
||||
List<Tree> trees = Arrays.asList(plasticTree, pineTree);
|
||||
|
||||
List<Tree> treeClones = trees.stream().map(Tree::copy).collect(toList());
|
||||
|
||||
Tree plasticTreeClone = treeClones.get(0);
|
||||
|
||||
assertEquals(mass, plasticTreeClone.getMass());
|
||||
assertEquals(height, plasticTreeClone.getHeight());
|
||||
assertEquals(position, plasticTreeClone.getPosition());
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user