2

我有以下类: Main 创建一个 Game 实例,它创建一个 Player 实例和一个 World 实例,World 创建一个 Floor 实例。

现在我想从 Player 中调用 Floor 中的一个方法,此时它基本上只是一个 getter,但以后可能会发展得更复杂。解决此问题的最佳方法是什么?在 Game 中创建一个调用 Floor 然后写入玩家的方法?我觉得在 Player 中创建一个新的 Floor 实例是不明智的。(但实际上并不知道。)而且我认为没有办法直接在我的层次结构中从 Player 调用 game.world.floor ?

4

2 回答 2

3

Player knows about World.

World knows about Floor.

To allow Player to access floor, do the following:

Implement this:

class World
{
    private Floor floor;

    public Floor getFloor()
    {
        return floor;
    }
}
于 2013-06-11T15:30:14.270 回答
0

You can use make the Floor Singleton like this

public class Floor{
    private static Floor instance;
    private Floor(){
        // do initial things
    }
    public static Floor getInstance(){
        if(instance == null)
            instance = new Floor();
        return instance;
    }
}

Now you can access Floor instance from any where by calling

Floor.getInstance()

It will always use a single instance of Floor no matter from where you are calling

于 2013-06-11T15:32:23.760 回答