OOD 面向对象设计有很大的几率出现在小公司的面试上,在youtube上找了一个很好的教程来和大家分享一下。
问题: OOD 思想设计两人投掷硬币的游戏。
步骤一: 准备documentation
游戏介绍:随机选择一个玩家,令该玩家预测硬币的正反面,另一个玩家获得和第一个玩家相反的选项。开始投掷硬币,预测正确的赢。
Actors: 1. 玩家A 2. 玩家B 3. 硬币 4. 掷硬币游戏
根据以上信息我们可以画出object model. 这个决定我们要创建多少个实体类。
根据游戏规则以及流程,我们可以画出类图。
步骤二:代码实现
Player class.
public class Player { private String Name; private String CoinOption; public String[] coinValue = {"Heads","Tails"}; Player(String name){ this.Name = name; } public String getCoinOption(){ return this.CoinOption; } public void setCoinOption(String opponentFlip){ this.CoinOption = (opponentFlip.equals("Heads"))?"Tails":"Heads"; } public String getRandCoinOption(){ int randNum = (Math.random()<0.5)?0:1; this.CoinOption = this.coinValue[randNum]; return this.CoinOption; } public void didPlayerWin(String winningFlip){ if(this.CoinOption.equals(winningFlip)){ System.out.println(this.Name + " won with flip of " + this.CoinOption); } else System.out.println(this.Name + " lost " + this.CoinOption); } }
Coin Class
public class Coin { private String coinOption = ""; public String[] coinValue = {"Heads","Tails"}; Coin(){ int randNum = (Math.random() < 0.5)?0:1; this.coinOption = this.coinValue[randNum]; } public String getCoinOption(){ return this.coinOption; } }
CoinGame Class
public class CoinGame { Player[] players = new Player[2]; Coin theCoin = new Coin(); CoinGame(String p1Name,String p2Name){ players[0] = new Player(p1Name); players[1] = new Player(p2Name); } public void startGame(){ int randNum = Math.random()<0.5?0:1; String playersPick = players[randNum].getRandCoinOption(); int opponentsIndex = (randNum == 1)?0:1; players[opponentsIndex].setCoinOption(playersPick); String winningFlip = theCoin.getCoinOption(); players[0].didPlayerWin(winningFlip); players[1].didPlayerWin(winningFlip); } }
main 测试类
public class main { public static void main(String[] args){ CoinGame theCoinGame = new CoinGame("Huazhe","meigtong"); String userAnswer; do{ theCoinGame.startGame(); System.out.println("Play again?y/n"); Scanner input = new Scanner(System.in); userAnswer = input.nextLine(); }while(userAnswer.equals("y")); } }
学习心得:个人感觉 OOD 体现的更多的是对问题由大到小进行分割的思想,将大的问题进行简化成一部分模块( object ), 然后对各个模块之间的交流进行组合已达到解决问题的最终目的。