haiyyu
haiyyu

Reputation: 2242

Firing an event without subscribing to it

I'm currently programming a library for simple games, mostly intended to be used by myself. Now I've run into a problem. I have a class called "Game" which looks like this:

class Game
{

    private List<Entity> entities;
    private int counter;

    public Game()
    {
        entities = new List<Entity>();
        counter = 0;
    }

    public AddEntity(Entity entity_)
    {
        entities.Add(entity_);
        // problem! how to inform entity_ that it was added?

        counter++;
    }
}

Entity is a class which each object that acts in the game must be derived from. Its contents don't really matter. What I am looking for is a way for Game to inform the newly added entity_ class about its owner (current Game instance) and its id (which is what "counter" is for). Now I have been thinking about using an interface which would have a method "OnAdd(Game owner_, int id_)" for that as that would definitely work, but I wanted to make sure there is no preferred way over that. So that is my question:

Is there a better solution for my problem than interfaces? The Entity instance does not know what Game instance it is being added to, and using methods for event-like purposes doesn't feel right in my eyes. I could be wrong if course.

Upvotes: 1

Views: 99

Answers (3)

ken2k
ken2k

Reputation: 48975

There are lots of solutions.

You could of course call a method after the .Add:

entity_.HasBeenAdded();

Another solution would be to "reverse the add". Something like:

Entity class:

public Entity
{

    ...

    public void AddTo(IList<Entity> list)
    {
        if (list == null)
        {
            throw new ArgumentNullException();
        }

        list.Add(this);

        // Do some logic here, as you now know your object
        // has been added.
    }
}

...

entity_.AddTo(entities);

Upvotes: 0

Roy Dictus
Roy Dictus

Reputation: 33139

If your Entity has a property of type Game, it's easy to solve this without even using events:

... code ...
entities.Add(entity_);
entity_.AddToGame(this);
... code ...

and then in the AddToGame method, you would do whatever you would do in your event handler, which now is not necessary.

Upvotes: 3

Pankaj
Pankaj

Reputation: 10095

Yes seems correct. But need to add a difference.

Interface - Once changes, you need to track down all implementation.

Abstract Class - Virtual functions can be declared so no need to keep track for the implementations

Upvotes: 1

Related Questions