Interaction between models MVC Java - java

I have a question about the MVC pattern.
I am creating a maze game in JAVA with swing and I'm trying to use the MVC pattern with it. So far it goes well but I don't get the "rules" of MVC.
Let's say I have two models: one for creating a maze and the other one for the player.
The player get's it's location from the maze created in the maze model. You see, the player determines it's location from that maze and decides if it can move to a new location.
This part I understand, But can my player model ask the maze model for the maze? or is it out of the question in MVC used in a java swing application? (interactions between models).
thanks!

öhm, this is one aspect of MVC that many people discuss all the time. For ME it just means that you have the really stupid VIEW-Part which does nothing else than showing Data and taking request. This Requests are forwarded to the Controller, which does some stuff with them and then call the MODEL to do the real work. So from my point of View, you are totally fine when Models talk to each other. But to rreduce dependency and improve encapsulation, i let my models get the other needed Models over the appropriate Controller, so i can use dependency Injection.
I see the COntrollers in my MVC apps as some kind of switchboard, which "regulate the traffic" and provide a place where you can call from inside the building to get a line to some co-worker, and from the outside you have to talk to the secretary.
I know other will say this is WRONG/RIGHT, but for me it works, even in teams.

MVC. Models only model your data and access that data. Views only serve the data to the user. The controller is like a conductor, putting it all together. Whether a model can be made up of another model, which I think you are asking, yes, but it might not be the best in terms of how tightly coupled your objects are. Is a player made of a maze object or just a location? Your question appears to be more about OOP principles than one of MVC. Unless of course I am miss reading your question.

Related

What is the correct structure of classes in java?

I have been coding in java for about a year and a half, and have made some small games and programs that I think turned out very well. The problem is that I am mostly self taught and I most of my code and class structure is not organized or "correctly structured". This didn't matter to me for the smaller things I made, but if I were to take on a larger project I would want to structure it correctly and make it organized.
In a previous mini-RPG game I had
Main Class (Main loop + Main method)
Player Class (containing player position and player stats)
Engine Class (containing map and collision detection between player and map
Map Class (containing map data)
My Main class contained an instance of Player and of Engine, and Engine had an instance of Map. The problem is that Player then could't tell the Engine where it was, and the Engine couldn't adjust Player's position and stats when something happened on the Map. So I ended up having some static variables and methods in both Player and Engine to get them to communicate.
I guess my overall question is is this the correct structure of classes, and is it correct to use static methods and variables here? If not, how would you structure these classes, or would there need to be more or less classes?
My overall objective is to understand how to structure classes in this previous game so I can better structure classes in a bigger project I want to take on.
It is a rather broad question, but the general answer is no.
As a rule you shouldn't use static fields to connect instances. (There are a couple of possible exceptions, but as a rule of thumb it's a useful one.) The basic idea of OOP is that everybody has a reference to whoever they want to send messages to. So if a Player needs to tell the Engine something, it should have a reference to whichever Engine instance it belongs to. Or you can redesign your architecture so only Engine sends messages to Map and Player, it's difficult to tell without more detail about your setup whether that would be appropriate in this case.
Another piece of general advice is to try to sit down with a piece of paper, write down the name of all three of your classes and in a separate column write down all the things the system has to do. And then you should try to figure out who's responsible for what. In a good design this decision is simple, if you find yourself shoehorning different things into one class, that's a sign that you should maybe need a more detailed model with more classes.
I would also suggest you take a look at the observer pattern and the publish-subscribe pattern, as it might be what you need.
Try take take a look at some design-patterns.
Which design pattern you want to use depends on what you prefer. Some can be found here on Wikipedia.
I also take it that you are familiar with OOP? Some more general info can be found here on Wikipedia.
Looking at your specific story, I think a MVC-design would be a nice solution.
MVC meaning Model View Controller.
Here you have your Model, classes holding different forms of data.
Your Controller, controls your Model, contains all the real logic.
And your View, this is the graphic end of your application.
You'd probably want to put and instance of your player in your engine as well. That way your engine will control everything (the player and the map). Hope that helps!
From what you described there a few possible ways to handle this. One would be to use a messaging system. I would look into Java Messaging Service (JMS). Another would be to make your app event drive. Here is a neat little tutorial on how to do this using spring : https://spring.io/guides/gs/messaging-reactor/. Having said that, if your intent is get a better understanding of problem solving using Java, I would first try and mimic these two approaches on your own, without any bulky frameworks.

Event driven board game and GUI: How to connect?

So I've been making board game Funny Bunny (children's game) on Java. I first made it text based but now I've been building a GUI for it using Swing. The trouble is, I've never made a GUI before and tough the GUI itself has been fairly easy to make, I find it incredibly hard to combine my game and the GUI.
I'll first explain the basic idea of the game.
THE GAME
There are 2-4 players and they all have four game pieces.
There's a deck of special card that "run" the game (4 types: move 1, 2 or 3 steps and card for changing the board.
One turn consists of player revealing a card
If it's a move card, the move a piece
If it's change the board card, the board changes and holes may open. (Some places on the board aren't safe, game pieces might drop in a hole)
So, the idea behind the game is fairly simple.
The trouble, I've got no idea how to actually make it work with a GUI. I tought it'd be rather and started enthuastically building my GUI. I made the game view (I'll add a picture), main menu, number of players menu and all that stuff just to realize that I don't know how to really make it work with event-driven game.
Game view, work in progress, never mind the colors
I'd like to GUI version work along these lines
1. First, bunch of menus for setting up the players and stuff. That's okay.
2. In the game view, player reveals a card by pushing "Show card"
3. Based on the type of the card enter either stage:
3.1 Move a game piece. This would happen by clicking a game piece (either button on the side or a piece on the game board) --> This would start move a piece process --> Requires updating the board in the end
OR
3.2 Change the board, which would updating the GUI board. I'm really lost with how to do this.
Should I use something like threads, or Swing Worker or what should I do?
Do you people want to see some sample code? That'd probably help. Just let me know, and I'll post some (it requires some translating with the comments and stuff and that's why I didn't want just randomly post parts of my code here)
All help, comments, feedback... everything would highly appreciated and really helpful. Did I already mention I'm lost and stuck? I really am.
You'll want to foster the concept of Model-View-Controller. The idea is to separate you program into layers of responsibility.
Model
The model is responsible for maintaining the data and stateful information about the program.
The model provides event notifications about changes to its state, which interested parties might need to know
View
Is responsible for representing the current state of the model(s) on the screen. It is also has direct connection to the user and is responsible for collecting user input which is handed to the...
Controller
Is responsible for binding them together. The controller takes input from the view and makes modifications to the model, based on it's rules.
The controller may even control information flowing from the model to the view.
In some implements of the MVC, the view and the model have no connection what so ever and only communicate via the controller. This is both good and bad. It's kind of bad as the controller needs to double up the communications coming from the model and pass them to the view, acting as a proxy, which can duplicate code. It's good as it protects the view and model from modifications which the controller may not allow for, based on it's rules. I tend to try and follow this model, but Swing itself hides the controller within the view, so it can seem more coupled.
This concept also relates to the idea of code to interface and not implementation. This means that the model, view and controller only know about the "contract" and not the details.
This allows you the flexibility to change the implementation (let's say, add network play-ability for example) without the need to change the entire program structure, as the components are only communicating with each other through the defined interfaces.
The overall intention here is to separate responsibility and allow each layer deal with it's own set of problems without mixing the through out the code. It also means that you can change certain layers over time with out adversely affecting the rest of the program, as they are not tightly coupled together
Now that you're probably completely confused, you could have a look at this example which demonstrates a login MVC
Not a while ago, I've made myself a card game in java.
Not gonna give specific code details cause that would be impossible here but the best advice i could give you is this.
Find a tutorial about swing. This will help you understand the basics of gui-making as well as the basic components available.
Also search about Listeners in order to make your gui work based on the logic of your game.
These things alone would be enough to create something basic (or even advanced).
Good luck with your project

MVC pattern vs Three tier - where does logic belong to?

I am trying to introduce some good practices into my website coding, so I started to look into MVC, since it is a buzzword in website designing :-) I am confused by the MVC pattern though. I am used to thinking in a Three-tier pattern, where you have 3 layers:
presentation
logic
data
Two things confuse me around MVC:
"Model" component is often presented as the data layer above (database abstraction). But where does the "high-level" logic belong to? Like deciding what you will do with the data and how, checking permissions etc. Sometimes I've seen some of this in the controller, but it is really confusing for me to decide which belongs where.
The MVC pattern is presented as a circle of 3 components which send messages to each other, like M -> V, V -> C, C -> M, and the other way around. I understand perfectly the Three-tier design, where one layer calls the layer below itself, but not the other way around! The functions in your programming language can call other functions (you can call it "sending a message") - but it is an oriented tree graph. But how can the lower layer, or, how can the called function "send a message" or "notify" the calling function?
Maybe I am too much concerned by the MVC pattern and could happily stay with my Three-tier designing? Anyway, I would like to understand MVC pattern to at least see if it is worth using for me.
The model is another way of saying your domain knowledge, your controller should be deciding what models to display, update, create, and your view should just present the data the controller has decided to present. To address your second question the model is normally passed to the view through the controller to the view for the data to be presented.
For more details scroll down the the Model View Controller section of this page

Model - persistence and service layers? True?

I am trying to confirm whether this statement is true:
Model includes both:
persistence layer: essentially DAOs + classes representing tables + DTOs
service layer: Combinations of DAOS + some logic
Could you also please reference/support your answer? I believed I've seen in Spring Framework good diagram, but no matter how searched this time I can't find it.
And the other point: I was always wondering why we abstract stuff so heavily that at some point people just stop understanding, is it done to increase our own value? :\
For example analysing Spring MVC I can say that central piece is controller no matter how you name other layers it is Controller who decides where to go what to extract , how to validate it and which view/controller to pass it on. Yet this simple statement is never found in formal articles keep confusing people.
So Controller is our god. Controller asking for some method within a class that call methods of another class. On top of it all is wired with dependency injection as we only need a single instance for objects of singleton nature. Controller>Service>DAO that's it .I would really appreciate book written by pragmatics.
If people would write books based on how things really are and not how to make look them beautifully drawn in diagrams or written the endless questions as such would never raise in a first place. And I thank stackoverflow for people that always show me the path. ;-)
MVC and the DAO/Service architecture are less concepts which are contained within each other than which sit next to each other.
In MVC, your controller takes care of fetching all the data, placing it in a model in some way, and passing the model to the view to be rendered. If you are also using DAO/Service architecture, your DAOs/Services might return an entity which contains all the information you will be displaying on a given page, and people often use these as the model for the view if things are relatively simple.
The problem with this tactic is you end up having dependencies between your views and the specific implementation of your model. Also, if you later decide you need some extra information which is not included in your model, you'll have to rewrite your view to account for this. This is why it is often suggested you do as much preparation of your data in your controller before passing a very simple model (a Map) to the view.
Here's a diagram showing the separation of layers:

How do you structure a java program? [closed]

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.

Categories