How to use observers

I have questions regarding the observers.
we have an add and a remove method in out tetrisgame for observers.
Should the remove method only remove an observer if it is the same as the one registered and if the argument is different just do nothing?

This part of the Specification confuses me:

The interface TetrisGame extends the interface GameObservable. Your implementation therefore has to inform
all registered GameObservers if any of the following events happen:

Does this mean we have more than one observer? because if this is the case we would need an upper bound for observers or we would need to manage the observers dynamically.
If we have one should add actually overwrite the old one?

3: should we add an observer when we initialize the TetrisGame? Since we call them on every step and every move or rotation of an piece this is currently an issue for my public tests, so we cant have 0 observers .

There can be many observers interested in the game.
For instance

  • One for logging the game to text files
  • One for an auto player to decide moves
  • One for the GUI to display the game

addObserver should add one additional observer that is notified of events.
removeObserver should remove the given observer if it was previously added.
All previously added (and not removed) observers should be notified for each event.

1 Like

No. You should have a List of them. See Observer pattern - Wikipedia

Does this mean that one Observer instance should be able to be registered multiple times or should this “list” behave more like a set of observers?
Especially what would be the behaviour of remove in this case? Would remove need to be called as many time as add or should it remove all these instances?

I’m going to say that we don’t test/specify this, so you can implement whatever behavior you want. But perhaps @Marcel.Ullrich2 knows better…

As an observer, you do not want to be notified twice about each event.
Therefore, a check whether the observer was already added would be nice.
The observer then would only be added to the collection of observers if it is not already in the collection.

The remove method would do nothing if it was added and otherwise remove the one instance of the observer.