我正在制作一些关于清洁工的游戏应用程序。它处于早期阶段,到目前为止我对此感到自豪,但是随着时间的推移,我的代码变得非常混乱,所以我决定过来寻求任何帮助,以另一种方式解决/重新制作/实现该代码,而无需这么多案例。我正在考虑实施某种设计模式,但我不确定是哪一种。如有任何帮助,我们将不胜感激。
bool JanitorApp::key(unsigned char key)
{
if (MainApp::key(key)) return true;
switch(key) {
case 'Q': case 'q':
current[0] = NULL;
status[0] = "Stationary";
return true;
case 'W': case 'w':
current[0] = &cleans[0];
status[0] = "Cleaning";
return true;
case 'E': case 'e':
current[0] = &eats[0];
status[0] = "Eating";
return true;
case 'R': case 'r':
current[0] = &guards[0];
status[0] = "Guarding";
return true;
case 'A': case 'a':
current[1] = NULL;
status[1] = "Stationary";
return true;
case 'S': case 's':
current[1] = &cleans[1];
status[1] = "Cleaning";
return true;
case 'D': case 'd':
current[1] = &eats[1];
status[1] = "Eating";
return true;
case 'F': case 'f':
current[1] = &guards[1];
status[1] = "Guarding";
return true;
case 'Z': case 'z':
current[2] = NULL;
status[2] = "Stationary";
return true;
case 'X': case 'x':
current[2] = &cleans[2];
status[2] = "Cleaning";
return true;
case 'C': case 'c':
current[2] = &eats[2];
status[2] = "Eating";
return true;
case 'V': case 'v':
current[2] = &guards[2];
status[2] = "Guarding";
return true;
}
return false;}
您可以从查看命令模式开始。用多态性重构替换条件也可能令人感兴趣。
//One of the ways to use the command pattern
public interface Command{
Player create();
}
public class CreatePlayerCommand {
private static final Map<String, Command> PLAYERS;
static {
final Map<String, Command> players = new HashMap<>();
players.put("TENNIS", new Command(){
public Player create(){
return new TennisPlayer();
}});
players.put("FOOTBALL", new Command(){
public Player create() {
return new FootballPlayer();
}});
players.put("SNOOKER", new Command(){
public Player create() {
return new SnookerPlayer();
}});
PLAYERS = Collections.unmodifiableMap(players);
}
public Player createPlayer(String playerType){
Command command = PLAYERS.get(playerType);
if(command==null){
throw new IllegalArgumentException("Invalid player type: " + playerType);
}
return command.create();
}}