I am very much new to design pattern. I'm trying to modify the Rock, paper, scissor game from an example book where I try to add more various design pattern. But I am encountering two similar switch statement which I think have duplicates and I don't have any idea on removing those duplicates.
A abstract class:
abstract class UserVsComp {
protected static Item item;
abstract protected Item getItem() throws WrongMove;
}
Here are the two switch statement:(First Class is for user movement)
class UserMove extends UserVsComp {
private String move;
public UserMove(String move) { this.move = move; }
public Item getItem() throws WrongMove {
switch (choiceValue(this.move)) {
case 0 : item = new Paper(); break;
case 1 : item = new Scissors(); break;
case 2 : item = new Rock(); break;
default: throw new WrongMove("Wrong move. Game end");
}
return item;
}
Second class is for Computer movement:
class ItemGenerator extends UserVsComp {
public Item getItem() throws WrongMove {
switch((int) (Math.random() * 2)) {
case 0: item = new Paper(); break;
case 1: item = new Scissors(); break;
case 2: item = new Rock(); break;
default: throw new WrongMove("Wrong move. Game end");
}
return item;
}
}
The two switch statement have same case (I guess duplicacy). I'd like to know if there is any way to remove this duplicacy.
ItemGenerator
class will beCompMove
class. Thanks for pointing that out and I will try to use composition instead of inheritance in this example. \$\endgroup\$ – Deb Feb 4 '15 at 12:59