What is the best way to access multiple objects in the same class - from multiple classes?

advertisements

Currently, I have a couple of static objects that I need to access from multiple other classes.

public static OrthographicCamera camera;
public static World world;
public static Player player;
public static TouchpadHandler touchpad;

It just doesn't feel clean or correct to repeatably access those from the other class, like this:

MainClass.world.blabla();

I've tried PASSING a reference to the desired object in a new instance's constructor. Something like this: (just an example)

    ... MainClass.java
OtherClassINeed obj = new OtherClassINeed(world);

    ... OtherClassINeed.java
private World world;
public OtherClassINeed(World world){
    this.world = world;
}

But this seems like it would be incredibly annoying/inefficient once you start needing multiple things (like the 4 shown above).

So I'm wondering: what's the best way to handle such a thing? Thank you!


I don't see using static members of MainClass a bad thing, you can do following if you don't like it:

class MainClass {
    public static final OrthographicCamera camera;
    public static final World world;
    public static final Player player;
    public static final TouchpadHandler touchpad;

    static {
        // initialize static members
    }
}

class OtherClass {
    public static final OrthographicCamera camera = MainClass.camera;

    // now access camera locally.
}

By the way I believe your main code smell is using statics, if you need singletons, convert them to object members (non final) and have a singleton instance of MainClass maybe using an IoC container.