1

There are already many useful answers about MVC. Most of the topics clearly state how controllers and view interact. A controller is aware of model but is the model also aware of Controller?

A concrete example: Suppose i want to move an object in game, A button is pressed, It sends coordinates to the controller along with the object whoms coordinates must be changed. (Suppoe model is a game class with few constraints, it either changes the coordinates or does not change anything, depending on the game state).

Now, controller has knowledge of Model so it asks the model to change the coordinates of the object. Can i give as parameter also the instance of this controller so that if game(class) effictively changes the coordinates, then game asks the controller to notify all subscribers?

So the question is: Is controller a subpart of the model?

  • The model should focus on the data. There's nothing wrong with say, having a gameboard model with chess piece models contained within and having the gameboard notify the chess piece models for a coordinate change. Though the notification is about keeping data up-to-date and consistent, not about performing logic. In other words, the model is the physics of the universe and the universe itself. God would be the controller. – Neil Mar 22 '18 at 7:30
11

Absolutely not. There are no reasons for the model to know anything about the controller.

If it happens that a change in a model should propagate an event, it's not up to the model to call the controller to do the job. Instead, the controller subscribes to the event within the model and reacts accordingly, either by responding to the event itself, or by exposing itself an event which will be raised in turn.

  • Thanks for the answer. I used this strategy from controller to view. Due to the constraint ,Controller calls the game(object) to do this and does not directly asks the object to move I will apply same from game to controllers. – Luai Ghunim Mar 21 '18 at 21:38
  • 3
    @LuaiGhunim: subscribing to an event is just one possible solutions, but often not needed. In lots of real world cases, it is quite simpler to let a method which starts an operation return a value about the success of the operation so the caller can act accordingly. For example, game->ChangeCoordinates(...) could simply return a boolean value indicating if the change really occurred, so the calling controller can react on that return value. – Doc Brown Mar 22 '18 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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