【问题标题】:Sharing of Model object across classes跨类共享模型对象
【发布时间】:2016-09-17 03:52:19
【问题描述】:

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

    }
}

【问题讨论】:

    标签: java oop object


    【解决方案1】:

    这样就可以了:Admin admin = new Admin(team);

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

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

    【讨论】:

      【解决方案2】:

      使用相同的对象/变量team

      Team team = new Team();
      
      Coach coach = new Coach(team);
      coach.deletePlayer(team);
      
      Admin admin = new Admin(team); // <-- here
      admin.addPlayer(team);
      

      【讨论】:

        猜你喜欢
        • 2015-02-28
        • 2015-02-17
        • 1970-01-01
        • 1970-01-01
        • 2012-10-15
        • 2010-11-29
        • 1970-01-01
        • 2012-02-01
        • 1970-01-01
        相关资源
        最近更新 更多