2016-09-17 132 views
-3

我有一個模型類Team。我需要在這個類上執行多個操作,例如CoachAdmin。我的問題是如何在創建所有其他類時同時維護對象Team跨類共享模型對象

TestDriver類中,我最初使用團隊對象創建Coach。但如果我想創建新的Admin,我需要通過相同的Team。我需要在這裏遵循什麼樣的模式?

//Model Classes 

public class Player { 
    String playerName; 
} 

public class Team { 
    List<Player> playerList; 
} 


//Class to modify model 

public class Coach { 
    Team team; 

    public Coach (Team team) { 
     this.team = team; 
    } 

    public void deletePlayer(Player) { 
     //Remove the player form team 
    } 
} 

public class Admin { 
    Team team; 

    public Admin (Team team) { 
     this.team = team; 
    } 

    public void addPlayer(Player) { 
     //Add the player to team 
    } 
} 

//Test Driver class 

public class TestDriver { 
    public static void main(String args[]) { 

     Team team = new Team(); 

     Coach coach = new Coach(team); 
     coach.deletePlayer(team); 

     //How to pass the same team 
     Admin admin = new Admin(???); 
     admin.addPlayer(team); 

    } 
} 

回答

1

這樣做:Admin admin = new Admin(team);

現在無論是admincoach實例將指同一team實例。所以無論你在team中做出什麼改變,都會反映在另一箇中。

您應該閱讀更多關於如何在Java中變量只保存對內存中實際對象的引用。

1

使用相同的對象/可變team

Team team = new Team(); 

Coach coach = new Coach(team); 
coach.deletePlayer(team); 

Admin admin = new Admin(team); // <-- here 
admin.addPlayer(team);