2
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .