I am having some troubles understanding and implementing the MVC pattern.
I have a singleton "model" class which contains all the datas of the application and extends Observable. When those data are modified, I want to update the views, and when one of the views receives some input from the user, I want to update the model. In between stands a Controller (implements Observer) which has an instance of both the view and the model.
I think that to do this, the views must have an instance of the controller. Whenever it receives an event from a button or any component, it calls the correct controller's method, which transmit the informations to the model. The model is updated and notifies the observer which in turn will update every components of all the views, even if they are not linked to the particular data which has been modified, since the Controller can't know what has been modified in the model. I am not sure this is a good design.
I looked a bit upon the PropertyChangeListener class, which seems to correct this issue but I am not so sure that I understand everything. Is there any preferred way to do this ?
Thanks in advance !
There are a few issues with what you're suggesting.
First of all, you're describing MVVM, not MVC.
The second problem is that the terms model and controller aren't suppose to describe singletons. They are merely terms to help you separate concerns by organizing your logic into classes with well-defined responsibilities.
The MVC structure is as follows:
The Model
This is your application logic/business rules. This basically means that if your application is about a phone book, then all logic and data structures that have to do with providing a phone book API is implemented here.
The View
This layer is completely separate from the model, in that it doesn't care about data structures or logic, but only on presenting simple values. Strings, integers, collections, you name it. But it doesn't care about the model's API, it only depends on the controller's.
The Controller
This is where things come together. The controller is the mediator. It speaks the language of the model, and that of the view, and it can make them work together. User requests are routed to the controller.
For example, a request might want to list all numbers in the phone book. What happens is:
The controller receives the request
Asks the model for all numbers that exist in the phone book via the model's API
[Optionally] converts the data into a data structure which the view is intended to display
Passes the data to the view
One last remark before we finish:
If the controller doesn't convert data from the model into something simple, then allegedly the view is now tightly-coupled with the model. However, that doesn't always have to be the case. Even if the model's API changes, then the controller might still be able to adapt the new API into the old API, which the view already understands.
Related
I'm working on a school project and or task is to design a project management tool. We are allowed to use any design pattern as long as we can explain how it's good according to the GRASP principles.
I'll give a synopsis of the project tool:
CRUD-functionality for projects
CRUD-functionality for tasks (a project has tasks)
CRUD-functionality for users (a user is assigned to tasks)
A simple GUI
We decided to go with the MVC-pattern and we are not allowed to use a database. My question is: Where should I store objects?
Should I do this in the controller? Currently we do it like this:
public class ProjectController
{
private ArrayList<Project> projects;
public ProjectController(TaskController taskController)
{
projects = new ArrayList<Project>();
}
}
I have a feeling there is something wrong with keeping the objects in the controller but I can't explain why. Anyone that can explain what's the best practice according to the GRASP-principles?
EDIT:
Thank you, learned from everyone something but can only pick one answer.
For a very short answer : NO, don't put your store in the controller. This is a bad idea and it goes against the MVC principle.
Usually, the model is the only place responsible for your data BUT it is frequent that the M part is split into :
Fetching the data.
Storing the data in the application.
The interesting part in this is that, no one cares where your data come from. A database, a file, an API rest. whatever, it doesn't matter.
I'm not saying i have the best solution for you but here is how you could do this with an example.
You store your user data into a file.
You create a php class UserDataRepository that fetches the user data files, and sets the data into your UserModel class.
From the controller, you call your UserDataReposiroty and get back your UserModel.
This way your controller doesn't have any idea how you are fetching the data. He just asks a repository to fetch them and it returns the UserModel that the controller is allowed to manipulate.
I hope this will help you
Increase abstraction.. Create a model class. Create your arraylist (model objects) there. Your controller should still access/call model methods.
Tomorrow, you might want to dump that data into a file or into a DB, you will have one hell of a ride doing that with the current design. So separate your model from your controller and keep the design clean.
No. If you store data in the controller then you are not using MVC. You have to do it in the Model. You can store in memory or files, but always store data throw the model. For example, you could implement DAO pattern to manipulate data.
Maybe, not now, but then you will need a database. With DAO pattern, it won't be difficult to adapt your current persistence kind to a database.
In MVC pattern, M means models, V means view, C means controller. A common MVC application progress is that once a request is coming, controller get it and do necessary processing, retrieving results data, then pass the results data to view for rendering. After view layer is rendered, it displays to users via GUI.
So controller can be regarded as a commander, it controls process, but it is not good to handle data retrieving in controller. Model should be responsible for retrieving and organizing data. That means data objects should be stored in Model instead of Controller, Controller calls Model to retrieve data objects. Take Java application as example, usually these parts are needed:
ProjectController, it calls ProjectService.getAllProjects() method to retrieve result. Once retrieved, view layer use the result to render GUI for display. I suggest Controller layer should be thin.
ProjectService, it has method getAllProjects(), this method calls ProjectDAO.getAllProjects() method to retrieve projects data, and maybe other handling. Here business logic goes.
ProjectDAO, it has several methods which deal with Project objects, deal with data in this layer! But these methods should be independent with business logic(as business logic should be deal in ProjectService).
Project object.
Hope it helps.
I have been working both on spring and grails (grails is built on spring).
We can pass our data from controller to view (jsp/gsp) via request object or via model.
Passing data via model is preferred because its easy.
Comparison of code :
Spring :
controller request.setAttribute("name","india");
view ${pageContext.request.getAttribute('name')}
controller ModelAndView("viewname",modelObject)
Grails
controller request.setAttribute("name","india")
view ${request.getAttribute("name")}
controller render(view:"viewName",model:[name:"india"])
I think request object does many functionalities other than this.
So my question is : If passing data from controller to view can be done with request object itself why java technology required to make a concept like model ?
necessity is mother of invention
I mean to say that there must be a task that can be implemented only via a model.
A few things come to mind, but they are speculation as to why.
Mainly, separation of concerns. Modifying the request, which is input, to hold output seems to be abusing this. The model is clearly ouput, and only output.
By clearly defining what constitutes output, using a model, frameworks such as Spring and Grails can then apply other processes to only the model. Grails filters come to mind, as an example.
That's my quick opinion.
That data which a controller gathers up and needs to make available to the view should be put in the model. That is kind of the definition of what the model is in this context. Never use request attributes for this.
we got: one abstract superclass containing one method, and two subclasses redefining this method according to their needs. Not sure how to sructure project following MVC modeling.
Like, what exactly class model should have inside, controller and view?
In the most simple possible implementation:
Your model class should do data access and no more; say for example that it should be the only one with an import java.sql.whatever, and return collections of beans fresh out from your repository.
Your controller class should call your model layer, extract information and take a decision about what to show the user and how to do it. For example: you can read a list of organization units and decide whether to send the user to a tree view of the units or, if there is only one unit, send them straight to an employee table with the people on that unit. Spring MVC controllers or Struts 1/2 action classes are nice examples of this. It should also leave the data available to the view in some accesible place (for example, as request attributes)
Your view should be a JSP (or whatever view technology you use) as simple and with as few decisions taken in it as possible; all data is retrieved and navigation decisions are taken beforehand for it, and its only mission is to paint.
I've been told that MVC is an architecture pattern for the presentation tier on a multi-tier architecture. I didn't understand the MVC Model concept.
So I made a web application, as an aproach to learn MVC model, only using JSP and Servlets, I made the DataAccess layer too.
In my WebContent folder, I put all the views.
In my src (Java content) folder, I made 4 packages.
data
presentation.model
presentation.controller
businessEntities
I used Servlets as Controllers (used the FrontController pattern) and JSP for all the Views.
As the title says, my problem is with the model.
Now, lets make an example..
I have 2 classes.
- Car
- CarLogic
CarLogic is a class that calls a possible CarDAO to get data and to return it to anyone who asks it. Car is just the POJO.
I placed CarLogic inside presentation.model and Car on businessEntities.
Am i wrong? What should i put on Model package?
Thanks!
When nested in the presentation layer of a multi-tier architecture, MVC's models are usually nothing more than (possibly enhanced) key-value maps.
The controller, after having called the appropriate business layer service, instanciate a new map with the values the view will have to display.
Spring MVC for example implemented the MVC pattern this way: see how the ModelMap extends LinkedHashMap.
See this answer to see a typical HTTP request life cycle, when the MVC pattern is nested in the presentation layer of a 3-tier architecture.
So to sum up, I would put CarLogic in your businessEntities package, and the Car POJO
within a new presentation.bean package for example (so you won't need your presentation.model package anymore). Thus, your controller would add the Car instance as an attribute of the request, which would then play the part of the model:
request.setAttribute("theBean", yourBeanInstance);
In your JSP views, simply use ${theBean.anyProperty} to access the attribute (don't forget the getter in your bean). Note that the EL will scan the following scopes in given order: page, request, session, application; the first found match will then be returned.
Model View Controller in and of itself is a pretty simple pattern.
From the wikipedia artical:
A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).
A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. In some cases an MVC implementation might instead be "passive," so that other components must poll the model for updates rather than being notified.
A view requests information from the model that it needs for generating an output representation to the user
At least it was simple pre-web and pre-SOA.
The view part is still pretty straight forward, it simply presents the model.
Controller-wise, the web, in its traditional http/html sense rather than the newer JavaScript/AJAX/websocket sense, has made the controllers iteraction with the view much more visible than it was in say a Swing application. This means in addition to their traditional role, controllers in a web-app are likely to not only interact with the model but also have some knowledge of the views.
Model-wise, pre-SOA the model represented both the data and the behaviour of the business. More recently anemic domain models have become popular with behaviour implemented in separate classes from the representation of the data, which is passed to the logic classes (services).
It's this point, relating to the separation of data and logic that I believe your question relates to. Personally, for simple systems, I prefer a rich model with the data and behaviour in the same classes, hence the packaging is simple. However I appreciate that sometimes the benefits in separating the logic from the data and in such cases I'd create a separate package (and probably a separate jar) to contain that logic.
The word "model" means subtly different things in the term "model-view-controller", and when you say "model layer" in an n-tier architecture such as yours. From the point of view of MVC, everything the controller passes input to, and fetches viewable data from, is the "model".
This includes your domain model (Car), and business logic (CarLogic). You don't need to necessarily structure your application to exactly match the pattern you're using on the UI side. (In fact, the MVC pattern is probably insufficient to cover an entire application to begin with.)
So in your case, putting Car into businessEntities is fine. Not sure about having presentation.model to begin with – business logic isn't a presentation concern, and probably belongs in a layer on its own. Which is where I'd put CarLogic.
I have no idea what the data package is supposed to be at all.
This split means there doesn't seem to be a dedicated presentation model in your application. This might or might not be an issue. In a web application, what the presentation model usually does is encapsulate user input, or maps the business entities to a structure that fits the needs of the view better – flattening complex relationships etc. (In classical Spring MVC, these would be the Command and Model classes.) In a simple enough application, or using an advanced enough web framework, it's possible to directly use domain model entities in your views.
As an example of what a distinct presentation model would do, consider the internal system a school would use. You'd have a bunch of students, and some classes they can enroll in. At the business entity layer, you'd probably have a separate Enrollment entity that would hold attributes like date of enrollment, references to the grades a student got in the class, etc. However, when a view in the application needs to display the list of classes a student is enrolled in, it doesn't really need to see the Enrollment object at all. Thus it makes sense to have a presentation model object Student that only has a list of Class objects in it. (And the requisite code that reads the business entities and maps them correctly to this structure.)
From Wikipedia about MVC:
Model–view–controller (MVC) is a software pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. The central component, the model, consists of application data, business rules, logic, and functions. A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants. The third part, the controller, accepts input and converts it to commands for the model or view.
I highlighted one sentence, that usually is not understood. The model is a really rich model. That means, it also contains every logic that works with the data. It is up to you, whether to have separate classes for data and for logic (which reduces the data classes to structs or records), or whether to have richer data classes that already contain some business methods (the way that I prefer).
That said, the controller is just the interaction between the model and the view. In Swing applications - for example - the controller is nothing else than the various listeners (an ActionListener, for example).
So, to answer your question: Having a separate data access layer is a good thing. This is where your DAO class belongs to. The data and logic classes (the model) belongs to the model package. I would not create several packages for them.
MVC is a common design pattern used by many modern web frameworks, f.e. GRAILS, Spring MVC or ASP.NET MVC. You see the MVC pattern is included in their names ;)
For the MVC-pattern you actually need three packages:
model
controller
view
In the model package you put your classes which will be used to hold your data. The controller classes contains the logic to controll which view is called and which data should be used in those views. The views itselfs contains the information how to display your data on the screen. There shouldn't be any great logic, f.e. just JavaScript. The business logic should contained in a separate package. If you need this logic, you can call is from your controller.
Your packages are (I hope i read them correctly!):
data
presentation.model
presentation.controller
businessEntities
According to the MVC-pattern is suggest the following usage of your packages:
"data" or "model" - use this for your Car class
"controller" - use this for your controller logic
"presentation" or "views" - use this for your views to display your data on the screen
"businessLogic" - use this for your CarLogic class
MVC stands for Model View Controller.
Model is where you store entity objects
View you store Presentation objects
Controller is where you map your attributes that are present in the Model to the widgets.
so that the attributes are set to the entity objects from the widgets input.
We are making a rather large Swing application which has to implement the MVC pattern.
The application currently looks like this:
There are quite a few views. They are created in a hierarchical manner where one main view contains (and creates)
several views which all contain their own set of sub-views, etc. Each of these views retrieve information from the model
independently from the other views, by calling the models static methods when necessary.
There are also quite a few controllers which are all totally separated from each other. Each controller
belongs to a view. Each view creates its own controller, and adds the controller as a listener to user input.
The controllers receive events from the views and then modify the model through the models static methods.
When the views dispatch events which do not affect the model, but only affect
the views, the views take care of these events themselves - without informing the controllers about the events.
That is, the controllers are totally unaware of the views, and the controllers purpose is only taking care of the manipulation of the model.
|EDIT: the controllers are currently attachments to their views; they only contain logic for event-handling. That is, the controllers are not components themselves, and do not contain components. They are implemented in the same manner as the following example: MVC example |
The model in the application is very passive, and does not even have listeners (it represents a database).
It receives updates from the controllers.
In this example, the views own the controllers. Would it be better in the general case if the controllers owned and created the views, and if one let the views be unaware of the controllers, instead of the opposite? In that case, why?
How would this be designed? If not, is there a better design in which the controllers are still unaware of the views? Or perhaps, is the best design neither of them?
EDIT:
As stated in the Original MVC definition:
the line "The View takes responsibility for establishing this intercommunication..."
seems to indicate that the view creates the controller, or at least has the initial reference to the controller, and not vice versa.
So this is at least a possible way to do it (it is a valid MVC pattern), but the main question remains; which is better, and how would the best design look like?
Especially when dealing with many controllers that are closely related to their respecive
views?
EDIT: Another example of a view which references a controller: Oracles example
As seen in this outline, the controller has the model and the view(s). Any sub-views are managed by the respective parent view. Sub-views may forward events to the parent as discussed here. There's a simple example here with more links.