问题描述:

I'm writing a plugin for this server and I need to create a list of players which can be accessed by several classes.

For example, there will be three classes:

Events

Commands

Plugin

The 'events' class will have a list of players that are online as well as their context (I cannot add this context to the player). I will need to access this list from all three of those classes.

I am unsure what to do, because I worry about the class loader messing with my things.

I've thought of making a global variable class with static accessor methods for the players and their context (thread safe) and just store everything I need to in here, but people say global variables are evil in Java and that this should not be done.

What should I do for this problem?

网友答案:

You could create a singleton class that contains the list that all the classes need to access, and then add that singleton as a composite member of all 3 classes.

The singleton design pattern is a global variable in a sense, but in an OO-friendly way that should work fine and not be evil.

网友答案:

You can encapsulate your player list in any data structure (lets say class Players backed by a Map or List or whatever structure is needed) and pass a reference of that structure to the classes that needs it (Commands, Plugins, etc) either by constructor or setter.

相关阅读:
Top