我正在開發我的Java任務 - 掃雷遊戲克隆。我有兩個幾乎完全相同的(只有文本標籤和文本框架不同的)方法gameWon()和gameLost(),它們負責在遊戲結束時顯示「遊戲贏了!」/「遊戲迷失」窗口。我知道代碼重複是不好的做法,所以我想優化它。問題是,我對OOP有點新鮮,我不確定如何去做。也許我可以將這些方法合併成某種方式,在不同的情況下采取不同的行爲,或者繼承可能會有用。我真的不知道,希望你們中的一些人能夠幫助我一點。感謝您的回答。Java OOP優化代碼
下面是這些方法的代碼:
GAMEOVER
public static void gameOver() {
F1 = new JFrame("Game Over");
F1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
F1.setSize(360, 120);
Container content = F1.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JLabel textLabel = new JLabel("Sorry, you have lost this game! Better luck next time.",SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(360, 40));
content.add(textLabel, BorderLayout.CENTER);
JButton button = new JButton("Exit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
content.add(button);
button = new JButton("Restart This Game");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
F1.dispose();
Board.doRepaint();
}
});
content.add(button);
button = new JButton("Play Again");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
F1.dispose();
restartGame();
}
});
content.add(button);
F1.setLocationRelativeTo(null);
F1.setVisible(true);
}
gameWon
public static void gameWon() {
F1 = new JFrame("Game Won");
F1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
F1.setSize(360, 120);
Container content = F1.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JLabel textLabel = new JLabel("Congratulations, you have won the game!",SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(360, 40));
content.add(textLabel, BorderLayout.CENTER);
JButton button = new JButton("Exit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
content.add(button);
button = new JButton("Restart This Game");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
F1.dispose();
Board.doRepaint();
}
});
content.add(button);
button = new JButton("Play Again");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
F1.dispose();
restartGame();
}
});
content.add(button);
F1.setLocationRelativeTo(null);
F1.setVisible(true);
}
你可以創建一個通用的'GameComplete'版本,它需要幾個字符串。這將允許您重複使用相同的代碼並顯示不同的文本 – Craig