Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I currently an implementing a game roughly using a model-view-controller setup. A single game controller instantiates a model and view. The model and view then instantiate child models and views, respectively passing references to the need models and view between them.

That works fine if the models and view are known at runtime (e.g. things that are guaranteed to exist such as the main character). My problem is when the model spawns game object models at certain times during gameplay (e.g, a randomly generated pickup). There needs to be a way for a view to also be created and the model passed as a reference to it. Of course, the model shouldn't have access to the view, but the view does have access to the model. What's a clean way to implement a system so that views can be dynamically generated and linked to their model counterparts?

One idea I had was the model can contain an array of "new" models that have not had views assigned to them already. When the view updates, it creates new views for each element in the array, assigns the models to themselves, and removes the element from the array. Thoughts? Thanks ahead of time.

share|improve this question

1 Answer 1

The model should indeed not have a direct reference to the view. However, the Observer Pattern can be applied here. The model has a collection of Observers. The view should implement the Observer interface. A view can add or remove it self from the model's observer collection. When a new model is created, the observers are notified and the new model can be given as a parameter.

In a way the model does have a reference to the view now, but it isn't aware of it. They are still loosely coupled.

share|improve this answer
    
Awesome, that makes sense. Thank you! –  user26691 Feb 24 '13 at 20:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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