跨类共享Model对象

时间:2016-09-17 03:52:20

标签: java oop object

我有一个模型类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);

    }
}

2 个答案:

答案 0 :(得分:1)

这样做:Admin admin = new Admin(team);

现在,admincoach实例都将引用相同的team实例。因此,您对team中所做的任何更改都会反映在另一个中。

您应该阅读更多关于Java中变量如何仅保存对内存中实际对象的引用的更多信息。

答案 1 :(得分:1)

使用相同的对象/变量team

Team team = new Team();

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

Admin admin = new Admin(team); // <-- here
admin.addPlayer(team);
相关问题