Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am confused how MVC will work with GUI swing application. I have worked with PHP MVC but that is totally different. I understand what MVC stands for. But what making me confused is different variation of doing it in GUI swing programming. It is hard to conclude particular thing from different articles in web. Who should know whom? I mean what will be the relation between model view and controller? Should controller know both model and the view? I would like to an simple example if possible to illustrate this (like and simple button which will update a label)
If i am not asking more i would like to get sugetions of MVC book which is writtern Swing in mind.
If you ask 10 different people "What does MVC mean?" you'll probably get 10 different answers. I'm personally partial to this definition of MVC (at least for non-web apps):
Model-View-Controller Design Pattern
Basically, the only functions the controller serves is to instantiate model and the view as the application starts up and connect them to one another. Everything else is just proper decoupling of your program's data and logic (model) from how you choose to display it to the user and allow user interaction (view).
There are many different interpretations of MVC for Java. I will try to provide a basic explanation, but as I said, others may disagree on this.
A theoretically 'pure' interpretation of MVC involves the following:
Model does not know about view
View does not know about model
Controller connects model and view in such a way that it provides data from the model to the view, handles 'events' in the view or the model, and updates the model accordingly based on what is happening in the view. It can also just handle an event in the view and provide a result back to the view, for example, a calculator.
Here is a possible/simple example:
The goal of this hypothetical application is to take a String in the model, get it to the GUI (view), allow the user to change the string, and update the aforementioned String value in the model. This example is more or less as decoupled as possible.
Model:
Contains a String variable
View:
Displays String variable.
Takes user input that allows change to the String.
Controller (the 'glue'):
Listens to Model via a customized listener for the String.
Provides this String to the view for the user to see
Listens to the view via a customized listener for the user to change the String.
Takes this new String and provides it to the Model, updating the original String.
One of the key things behind MVC is the Observer Pattern Theory.
Although one takes certain risks using wikipedia, it generally does a good job conveying the basics behind MVC. http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Here is the link for a discussion on the 'pure' implementation and the source of the interpretation.
http://www.youtube.com/watch?v=ACOHAR7PIp4
Here is a link with a very good explanation of a similar MVC interpretation and the theory behind it:
http://www.youtube.com/watch?v=CVxt79kK3Mk
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 days ago.
The community is reviewing whether to reopen this question as of yesterday.
Improve this question
I have a simple ATM system implemented in Java using Swing (I know Swing isn't really used anymore but I wanted it to be simple). The way I implemented it is as follows:
I have a Customer class which holds information about a customer and has a login() method
I have an Account class which holds information about an account and has methods for withdrawing, depositing and transferring money
I have a Transaction class which holds information about a transaction and has a generateReceipt() method that creates and exports a PDF with transaction info
I have an ATM class which holds the logged in account and the corresponding customer and has static methods for getting transactions, such as the current account transactions
Finally, I have an Admin class with username and password as attributes and methods for getting all the customers and accounts, adding a customer or creating an account and deleting a customer or an account.
My application uses a MySQL database for storing information and making updates. Also, customers can have multiple accounts and one can log in the system using the account number and PIN.
I drew the use case diagrams, and the class diagram, not considering my UI in the class diagram.
I have a hard time creating sequence diagrams for this application, as all my classes and objects are used in classes made with Swing.
My question is: how should I structure my sequence diagrams, considering the fact that it is a Swing application? Should I add the UI classes or should I make it more conceptual and only describe the process and relations between my other 5 classes?
Any help is highly appreciated!
I tried separating as much logic from the actual UI, but I still can't figure out how should my sequence diagrams look, as a customer and the admin interacts with the Swing frames.
The class diagram without any of the app's internals is a "domain model". Its goal is not to document all possible classes used in your apps, but to focus on the domain knowledge, independently of how the app is implemented. The diagram would stay the same if you had a real ATM device, if you would implement a web service, or if you would use any other UI framework.
So you made a clear choice on what you wanted the diagram to show. You could perfectly have chosen to have monstrous class diagram including in addition the classes required for the business logic, for database interaction and for the UI (e.g. using the famous Entity Boundary Control pattern). The diagram would then be more dependent on your implementation choices.
For the sequence diagram, it's the same. There is no best way to draft this diagram. The question is only about what you want this diagram to focus on: do you want to model the domain logic ? In this case you would use your domain classes and show how they interact. Or do you want to model the detailed application design , in which case you could envisage to add also UI classes. But the diagrams would then quickly become very complex, and you'd better break them down into several simpler SDs, each focusing on some parts of your detailed technical design.
The MVC pattern component interactions are described this way on Wikipedia:
The model is responsible for managing the data of the application. It
receives user input from the controller. The view means presentation
of the model in a particular format. The controller responds to the
user input and performs interactions on the data model objects. The
controller receives the input, optionally validates it and then passes
the input to the model.
I understand that the View should not be able to interact with the Model. But in most of the diagrams I find on the net, MVC is represented like this:
We can see that Model does interact with the View and is able to modify it, and it doesn't make sense.
Doesn't the Model update the Controller, that updates the View?
What am I missing?
The MVC architecture was created in the 1970s. Obviously there was no Internet at that time. In the original version, the Model directly updates the View through data binding, also known as publish/subscribe, also known as the Observer Pattern.
The Gang of Four Design Patterns book describes this MVC architecture in detail. A couple of quotes from that book are in another answer here.
The MVC architecture was very popular, and when the Internet came along, developers wanted to continue using it; but it didn't fit nicely into client/server applications. Thus was born "WebMVC", the version you most commonly see today. WebMVC is typically implemented as a layered architecture, which the original was not.
Confusion ensues when the two architectures are conflated. Often both are referred to simply as MVC. Even worse, related architectures such as MVP and MVVM can be called MVC.
Personally, I find the relationship between desktop MVC and web MVC somewhat like the relationship between Java and JavaScript. The latter piggybacked on the famous name of the former, to implement something significantly different.
related: Is it MVC when the view doesn't interact with the model?
No you can't access view with model directly, you must access controller first
as its MVC Pattern
Diagrams - worth a thousand words! The precise words and context used in the diagram maybe doesn't tell a story of implementation, say in Microsoft MVC 5/6.
A user's interaction is with the controller. Not the view and not the model. Calling an action on a controller will return something (a view, a file, a redirect, etc.).
In the case of returning a view of information, the controller, having worked out what data the user is requesting can retrieve a model that fits the request, pass this into a view, and return the view result of this model.
In the diagram above it isn't clear that the controller is acting as the agent in moving the model into the view. the model does not decide on the view. Why? Depending on what is in the model returned the controller, a different view might be returned. That is why the controller is aptly named. It sits at the centre of affairs making decisions and moving objects around.
So what you are missing is some context about how the process of MVC occurs when implemented
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
From week I have been searching of a true explanation and implementation of MVC using java, but something i have noticed is that every one implement it differently, so I would be grateful if you give me a useful link or e-book about it, and I need these questions to be answered :
How to inform the modal of the changes happen on the view, since the modal is observable adnd not observer ?
How to inform the view of the changes happen on collections (adding an item to an arraylist), because to add an item this will be happen on the controller handler and the controller is not observable.
Is it a must to work with MVC in the big projects.
The basic idea is:
The trigger for change can be either the controller
(=response code for user inputs, such as keyboard/mouse clicks), or application
decision. E.g. if you have a text field showing a price, the trigger to change it could
be explicit user typing, or a message from the bank.
each such trigger updates the model (and the model only).
In my price example, it would change the model (that backs the text field).
On change - the model fires events, which cause the view to re-render
Thus, to your first question: there's no need to "inform the model that changes happen on the view". The view shouldn't change on its own. The closes thing is keyboard/mouse clicks, that would invoke the CONTROLLER.
To your second question: "how to inform the view of the changes happen on collection" - the collection should be in the model. The controller would then do "model.addItem" which would fire an event for the view
Regarding the use in big projects... you'd probably get different opinions on it.
"Atomic" components would most likely follow this pattern strictly (button, textfield, or similar custom components). The debate would be about larger scales with complex/compound data. E.g. if my main logic resides on a database, how to I inform various screens that something changed. Both the screen and the database hold complex compound data (e.g. user plus his product recommendations plus shopping cart), and you need to decide on the granularity of events : on some simple applications I settled for the application layer sending 'Entity-level events' (such as 'user changed', 'product changed') to which the UI layer registered directly, so it wasn't 100% classical MVC. On other cases I took the trouble to build a compound Model that exactly reflects the screen data.
For the first part, I advise you to start at Wikipedia page on Model–view–controller. You will find a decent explain and other links.
For your first questions, you simply have to think about the workflow. The interaction with user occurs is the view. Then on an action of the user the controller takes the input, optionnaly reformats and passes it to the model in a format known to the model. In theory, the model then updates the view (in web applications, the controller collects data from the model and passes it to the view, so the update model -> view is indirect).
For the second, if you are in a situation where the model can directly update the view (Desktop application or specialized components such as java applets) no problem. If the model cannot directly update the view (typical in web applications), the update will be visible on next interaction. And in fact it happens exactly this way, when you see a web page with gauges displaying values constantly up to date : the browser is instructed via javascript or html meta tags to refresh its state at short time intervals. But when you say to add an item this will be happen on the controller handler, it is only true is this is caused by an interaction from the user (and the view knows it has to update its state, or is instructed to do so via the controller). But the model can be modified by many other ways, interaction from other users, real time probes, back office operations, etc.
The third question is a bit a matter of opinions. What is true is that separation of concerns is recognized as a good design because the different layers can be developped and tested independently (ot a certain extend). That separation allows to change technology in one layer without changing the others (even if this is often theorical). But IMHO the greatest benefit is that you have plenty of frameworks implementing MVC pattern. Choose one, and the greatest part of boiler plate code will be offered by the framework without you having to write and test it. All that giving a reduction of developpement time and of possibilities of mistakes.
My conclusion will be that (like others said in theirs comments) what is important is understanding the theory and the theorical benefits of MVC patterns and separation of concerns. Then depending of what you have to develop and you environment (technologies knowned or allowed) choose a framework that will exempt you to write boiler plate code, and spend the saved time to carefully analyze what all that is for, and what users expect.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I am looking for a tutorial / book that guides me to understand the Controll functions and the best practices to write my own controller + Model
Thanks in advance.
Here are some useful links,
Model View Presenter in MSDN Magazine (To know the difference b/w Presenter and Controller look at Martin Fowler's: GUI Architecture)
MVC from Oracle
Another MVC from CodeProject
Building Graphical User Interfaces with the MVC Pattern
Im sure theres plenty of links been posted to get you started but some important factors in creating an MVC is:
Static Registry Class (Store objects and fetch with a global scope)
Router (A class that determains the controller/method and params from URI's)
Base Controller (just a small abstract class then the users controller can extend)
SPL Auto-loading (this will allow users to extend classes such as Model_Database)
Structure (you should create directories in accordance with names, I.e Library_session would load /library/session.class.php)
Model Abstraction (Account for all types of storage, Database, Disk etc)
Error Tracking (Always make sure your logging and capturing errors)
They are just a few tips and ideas you should be thinking about when you create your system.
What you should also do is user other frameworks and build some sample projects, learn how an MVC Framework should be sued, so when your building one you know what the user should expect, then just really study the core structure of the framework.
Take into consideration in PHP the following are usually how MVC Works
Controller (this is executed depending on the URI)
Model (Accessed from the controller and should be the I/O of Data)
View (Templates basically)
but you can work with a MVCL which is (M odel/V iew/C ontroller/L language)
Language is not a specific in the original documentation but its been adopted a few times in regards to the pattern structure, An example of the file structure below will guide you into whats the main purpose of the +L
M: \catalog\model\catalog\product.php
V: \catalog\view\template\product\product.tpl
C: \catalog\controller\product\product.php
L: \catalog\language\english\product\product.php
An example of what company / project uses this method is: OpenCart, AND I HIGHY RECOMMEND YOU LOOKING AT THE ARCHITECTURE!
Here is a hopefully helpfull link to an article.
and here is a link to a very descriptive tutorial.
Why not trying codeigniter?
It is a Model View Controller based Framework.
In combination with doctrine its pretty usefull.
Here the link to some codeigniter tutorials: codeigniter tutorials
You're question basicaly a design patern question, a realy good book about this subject is:
Architect's Guide to PHP Design Patterns
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
For quite awhile I have been trying to make a simple "game" in Java that is really just an applet with a square and a grid. What I want it to do in the end is the user clicks and the square will move to where the user clicked rounded to the nearest grid square.
The problem is I am a self taught beginner and I am having a hard time figuring out how to actually structure the program, some examples:
should I have a separate class listening for mouse clicks?
When I receive a click should I send it to some other object that represents the box and let it decide what it wants to do or just call some function that makes the box move?
I really want to learn all this "when to use what" stuff for myself so any links or general advice is appreciated.
What you're really asking is how to develop a game, which is notably different from a typical Java application. However, I'll give you a few ideas to at least point you in the right direction.
Take advantage of the fact that Java is an object-oriented language. That is, objects should each have their own responsibility.
Separate your game into three key layers: the application layer, the game logic layer, and the presentation layer.
The application layer should contain all of your helpers and generic subsystems, things like random number generators, text parsers, file access modules, mesh loaders, etc.
The game logic layer should implement all of the rules of your game, and be responsible for maintaining canonical state. Basically, when you press the "W" on the keyboard to move forward, the game logic layer should receive MOVE_FORWARD_REQUEST from the UI.
The presentation layer should be responsible for two things: getting input, and rendering your world. When it gets input, like the "W" key, it should map that to an action, and send that to the game logic layer to be processed. Then, it should render the world based on whatever the game logic told it to do.
Game development is obviously an entire realm with many books dedicated to it. One of my favorites is Game Coding Complete, which does focus on C/C++, but should give you a good idea about how you ought to structure your game.
Good luck!
One main principle of good software development is the Single Responsibility Priciple. It states that a function or class should only have one responsibility.
This way your classes and objects shouldn't become too big and unmanageable.
I think one of the most important concepts to master when developing software is the concept or Orthogonality. It's not the simplest definition, but in essence it means that one component (such as reading mouse clicks) shouldn't be directly tied to an unrelated component (moving a square on the screen).
In your case, the code reading mouse clicks should be separate from the code that actually moves the box. Whether you implement this as inner/anonymous classes or not is up to you. But if you follow the Orthogonality principle, it will be easy to change at a later date should you change your mind.
One problem here is that all the rules have some leeway in them where you have to use your own best judgement.
For example, the app you are describing now seems to me so simple I'd probably do it in a single class, with perhaps a couple of nested, perhaps anonymous classes. In any event, I could make a decent case for fitting the whole thing into a single source file, claiming that multiple source files would actually increase the complexity of the whole thing.
But if your GUI had a number of different controls, perhaps each controlling different behavior, it would become time to split the functionality up so you're not ending up with a big bowl of spaghetti code.
The Java GUI libraries try to naturally separate (view+controller) from model. You are encouraged to define and display the GUI in one module (= file) but to have your data model and perhaps functionality in another. For complicated GUIs, there may also be multiple GUI implementation modules held together by code.
One way to keep things "clean" is to work in "layers" where each layer "knows" only what it needs to know. To be specific, the GUI layer needs to know about the existence of its underlying models – tables and lists and whatnot need to be connected to TableModels and ListModels, etc. It doesn't need to know about details of these models though, so it can simply refer to those models by interface.
The model layer, on the other hand, need know nothing about the GUI. The less it knows, the better, and this would theoretically enable you to exchange GUIs without needing to touch the models.
My model can also contain ActionListeners to respond to actions undertaken by e.g. pushing buttons in the GUI.
Of course, actions and changes to the model will often result in changes to the GUI. How to communicate these changes to the GUI if the model layer doesn't know about the GUI? You can use bound bean properties here. Here's a short tutorial: http://www.javalobby.org/java/forums/t19476.html . So you have the same kind of structure: Changes happen in your model, they're communicated to beans with property change support within the model, and the GUI can attach listeners to those properties to find out something changed.
Whether you perform actual, effective actions (e.g. writing files, converting data, whatever) within your model code or whether you split "processing" code off into yet another module is up to you and will again depend on how cluttered your model already is. If there's a tiny handful of fields and methods feeling lonely in there, you may decide to mash things together but the moment it starts to look messy you'll want to refactor your processing code out into its own module. Processing sounds like the kind of module that doesn't want to know about other modules either; you may end up just calling its methods from the model level.
I've described my basic style for doing GUI development. There are certainly other recommendations out there, and you will likely develop your own style based on your experience. This is just intended to give you an idea and a possible starting point.
Step 1 - find the demo applets supplied by Sun. http://java.sun.com/applets/jdk/
Step 2 - read those demo applets. At least three. Preferably all of them.
One you've read several applets, you should see a little more clearly how to organize programs. You can then ask questions with a lot more focus pointing to specific applet examples and your specific programming problem.
Yeah, I'm a beginner programmer myself. Yeah, segregating functionality across multiple classes is a good way to reduce complexity and increase cohesion of individual classes.
Increasing cohesion good because by having more complex data structure your algorithms become less complex and your code is less dependent on each other.
For instance in your case it might be a good idea to separate the classes in accordance to MVC (Model View Controler).
You have a Model which represents the way your game data is structured.
You have a Viewer which present your Model in what ever form you please.
Have a Controller which picks up changes in the Model (via Listeners) and then updates the Viewer
Now you can change your Model and add extra functionality requiring only small changes in the way the Viewer works.
There are many Patterns out there but there isn't a hard rule when to use one over the other. There are some cases in which you can use several and there are cases in which will require you to chose one design pattern over the other.
Every beginning Java programmer should start with the Sun Tutorials. They are quite good.
Another good source, especially among free sources, is Bruce Eckel's "Thinking in Java", available from http://www.mindview.net/Books/TIJ/.
But the latter is a little dated compared to the former. That is why I recommend both.