Petre Popescu
Petre Popescu

Reputation: 2002

Event Dispacher in Java

I need to to make for school a simple "strategy game simulator". To do this I need to make an Event Dispatcher (event loop) that will send the event to the registered parties. For example, I have resources on the map. One event is "resource at location 1 depleted". And one "player" is interested on that event. How would I create the dispatcher (and register one player for one particular event). Also, how does the dispatcher check for the event? Does it simply do something like if(resourceLocation1.getNoResource()==0) trigerEvent(); or is there some other, more elegant way.

I worked with event listeners (mostly in ActionScrip3) but never made a custom event and a custom event dispatcher. Any help is appreciated, including some links to some tutorials or sample codes.

If I am not clear what I am searching for please let me know and I will try to explain it better

Thanks.

Upvotes: 1

Views: 1881

Answers (3)

Garrett Hall
Garrett Hall

Reputation: 30032

Your EventDispatcher does not need to check every possible condition and notify all possible listeners. Just notify listeners registered for a certain type of event.

Register Player to be notified depending on the game event

eventDispatcher.register(player, Events.RESOURCE_DEPLETION_EVENT);

Then your Resource would supply an event when resources reached 0

class Resource {
    public void deplete(int amount) {
         this.amount -= amount;
         if (this.amount <= 0)
             eventDispatcher.notify(this, Events.RESOURCE_DEPLETION_EVENT);
    }
 }

Otherwise you are going to end up with a massive logic-containing event loop that eats up performance and will be difficult to debug.

Upvotes: 1

Bryan
Bryan

Reputation: 2211

What about implementing an observer pattern?

For instance, you can have a ResourceObserver, which registers a particular Resource as an observable. From there, you can have Player objects register as observers to your ResourceObserver. A map object will hold all the resources. In your event loop, you will have something like:

...
Map.updateResources();
...

So for instance, when you call updateResources, all the map resources will check if they have been depleted. If a resource has been depeleted, it will notify it's ResourceObserver, which will in turn notify all registered players for that resource.

Upvotes: 1

Garrett Hall
Garrett Hall

Reputation: 30032

Java has a built-in thread-safe Observer pattern you can use.

To write your own you would have Player implement a ResourceDepeletionListener interface and add it to an array of listeners in your Resource class. When the resources reach zero they call resourcesDepleted() on all ResourceDepeletionListener objects.

Upvotes: 1

Related Questions