Mike
Mike

Reputation: 779

Globally accessible object?

I'm making a small rpg game, and have implemented a sort of observer design pattern for event driven communication between objects. I have an EventManager that registers listeners, accepts new events, and dispatches events. The issue is that every object that needs to send or receive events requires an instance of EventManager to call addEvent() or register(). Since almost every object in my program will be using this system (to decrease coupling and avoid data modification errors) I need a good way to access it.

Currently I'm passing the reference explicitly to tons of objects in their constructors and methods, but as scale increases this is getting messier. Especially since I'm beginning to need it in objects like Character, and characters are not constructed in-game; they are deserialized from a data file.

I know global variable are bad design in general, but these are the options I can see, all of which are criticized:

a) make every field and method in EventManager static

b) go with a singleton design

c) make a public static EventManager

Any ideas? Thanks

Upvotes: 0

Views: 1706

Answers (3)

Bryan
Bryan

Reputation: 963

Dependency injection frameworks (Google Guice) provide a good way to manage references across larger applications. This has the benefit of allowing you to focus more on how you're using your objects than on how you'll get a reference to them in addition to allowing you to change your application (say you wanted 2 event managers or one for each player) by only updating the relevant export module.

It also allows for easier unit testing by decoupling your classes from their dependencies (if you have a singleton event manager, it will be much harder to use a mock framework to test each class without having to construct an entire object hierarchy.

Upvotes: 0

Michael
Michael

Reputation: 1012

I would recommend static personally. Big difference between static and singleton. I'm a fan of injection, but not so that a class that receives the dependency then can pass it on. Just my own thoughts.

Upvotes: 0

Antimony
Antimony

Reputation: 39501

Actually, what you're doing currently is best practice. Dependency injection is important, not only for modularity, but also for testing. You can reduce the burden of passing the parameter around by using factories.

If you were to use global variables (Which you shouldn't), the way to do it in Java is static public fields of some class.

Upvotes: 2

Related Questions