4

TBH: I've never used an observer pattern. But it looks pretty useful for this situation:

I'm developing a very simple strategy game. It involves two combatants who simultaneously bludgeon each other over a short period of time, the winner being the combatant with the most health remaining in the end.

Now, there's a lot of configurable strategies for the combatants, different pieces of equipment that can change how often they attack, etc. I'm also planning on including some "outside" factors like weather that will affect the combatants.

So.... I could create a Fight object that is the subject. It keeps track of the time and notifies the observers every "tick" of the clock.

The observers are two instances of a Combatant object and one Weather object.

It seems like a good idea, but where are the pitfalls? Actually, as I'm typing this I think one problem is that observers are probably ignorant of each others' parameters. Or must they be?

Has anyone used an effective design pattern to do something like this?

5
  • What's a "tick of the clock?" Is it an arbitrary countdown timer? Or do you mean the tick of a game loop? Commented Oct 15, 2010 at 21:47
  • It's an arbitrary timer. The idea will be to loop through the fight, store the results, and then display the play-by-play to the user afterward.
    – Stephen
    Commented Oct 15, 2010 at 21:50
  • 1
    this would probably be a better fit for StackOverflow
    – Muad'Dib
    Commented Oct 15, 2010 at 22:18
  • @Muad'Dib Really? I figured StackOverflow would tell me to bring it here due to the subjective nature of the question.
    – Stephen
    Commented Oct 16, 2010 at 4:36
  • 2
    Nah, they would most likely accept this at StackOverflow. This is a direct programming problem-related question and discusses programming solutions. One solution may be equal to another where the choice between them is subjective, but the discussion of the overall problem itself is not as some solutions are clearly not applicable. So this question does have one or a few good answers, whereas questions such as "Which is the best text editor?" does not (unless such questions are narrowed down to a single feature of function).
    – gablin
    Commented Oct 16, 2010 at 8:17

1 Answer 1

4

If the two Combatant instances and Weather object are notified as the result of the clock tick count being updated, and not by direct intervention by the Fight object, then it's the Observer pattern.

If your Fight object triggers the notifications directly you can use the Command pattern to encapsulate the receivers or have the Fight object send messages directly to the Combatants and Weather objects individually.

1
  • I ended up using a command pattern.
    – Stephen
    Commented Oct 22, 2010 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.