When should and shouldn't I extend a class, and is it valid for MVC?
I am considering using class extension as a way to connect my model with my controller. I tried looking on the internet but could not find any information on this topic. This 开发者_JAVA百科led me to the question of when a class should be extended and for what reasons.
This is my plan:
- model class
- controller extends model
- new controller();
- new view(controller);
Reason: I can make all methods and variables that the view should not touch or alter protected (i.e. protected var myVar:String). This enables me to ensure that the view still has access to the data it needs but is unable to make accidental changes.
This whole thought process derived from the fact that I don't want my view to have any influence whatsoever, while still remaining independent (i.e. I can have multiple views of the same model without having to tell the controller that an additional view has been added).
To summarize:
- When should a class be extended? When should it be avoided?
- Is my plan a valid implementation of MVC?
- Is there a better way to disconnect the view in a way that meets my demands?
Thank you for reading till the end.
The controller shouldn't extend the model - they do two separate things in the MVC triad and therefore should be two different classes. A valid reason to extend the Model class would be to add an extra feature to it, for example BigModel
Heres a summary of each part of MVC structure
- The model manages the behavior and data of the application domain
- The view renders the model into a form suitable for interaction, typically a user interface element
- The controller receives input and initiates a response by making calls on model objects.
Your view will not have access to the protected methods of the model/controller. Protected does not mean read only, it means that only classes that extend the base class can access the protected properties or methods.
To have read only attributes in your model you should look at using private/protected properties and then creating a public getter function for each property (Property can then be read but not set).
Also to have access to the model from the view consider creating the Model as a Singleton so it can be accessed from anywhere in your application.
The controller dosen't usually do much else than listen for and dispatch events/notifications, sometimes for small projects you can make your Model class (Singleton) extend EventDispatcher and have it pretty much do everything you want, but this is not pure MVC and can quickly lead to technical debt if the project scope grows.
精彩评论