Java E-Shop project - java

So I have an exercise about creating a functional e-shop with a minimal CMD UI. I have certain instructions and rules to follow while creating this and that's what makes it so difficult for me.
So firstly I have to create a class ierarchy, at the top of which stands the general Product.class and then below that the sub-classes Motherboard, CPU, GPU etc. Each of these sub classes contain their respective constructors. However, in the description of my exercise it isn't stated which items are going to be avalaible for immediate sale or should be ordered. Thus, I think that I'm supposed to choose these randomly meaning that I will have to create each and every one of these 'objects' by calling their constructors, like Motherboard mb1 = new Motherboard(motherboard info). Is there another way of implementing this? Because it seems like it's not the best way.
Now for my problem, say I have the required objects created and through the UI and consecutive questions the user will choose what product to buy, how am I going to 'transfer' this chosen object to my Sale.class so I initiate the sale and go on with the program?( The sale class has to print the item's info which is stored in its object and then reduce the items quantity from the shop's reserve)
Thanks in advance!

Your sale class should have a reference to the listed items. This probably should be a List or a Set.

Related

Object Oriented Approach for a Supermarket Simulator

I have been learning java and data structures in java lately. I am dealing with this problem , this would be the first sort of real program i will be coding up . Up to this point i have only wrote code for short algorithms and data structures. So i was kind of looking for guidance on how i can approach this step by step. I am not looking for any code as i don't learn by looking at other peoples codes rather i needed guidance in how i should approach such a problem ..ex. do i first determine which classes i need etc? So after surveying the problem i realize this problem can be made as detailed or complicated as we like but i am trying to keep it simple do the basic that is required. So the following is what i have gathered so far.
I need a Customer class that will include name, age, number of grocery items bought, and method for determining which queue to join(join the shortest queue).
I need a several Customer queues that are associated with "checkers" who take random time to process each customer.
I would need a supermarket class where all the interaction between the customer, the queue and the checker would take place.
I am confused as i don't know where to start at the moment and also right now i don't have a clear idea on how everything will come together. I would really appreciate if someone can provide me step by step guidance as to what i should do in which order. By doing so it will help me in the future when i write more code for other object oriented languages.
I highly appreciate all inputs and apologize if have asked anything inappropriate.
In general, you need a main loop that repeats over and over and handles input and all entities you have (customers, groceries, etc.)
Since you want the supermarket class to manage your program, I would start with that.
You will then realize that you need a customer in your supermarket.
So create that class when you need it.
Then you will realize you need groceries.
So create that class when you need it.
Then you will realize you need to create the instances for these classes.
That would happen inside the supermarket in your case.
So far, nothing has been made 'viewable' and no interaction with the program is possible.
It creates customers themselves. Adds groceries to them (e.g. in an ArrayList property of the customer).
Then you will realize you need Ques.
So create them.
Time for each customer could depend on the number of items times a random factor.
Now you have your supermarket running. You should add debug logging that you can maybe turn off so you see what's happening.
Now, if you want, you can create something where you can view the supermarket's statistics or however you want to visualize.
Then, create the input for the user. Remember that you are running an infinite loop. You can ask for user input on each iteration. When input is present, react accordingly.
Now: fix bugs, add features, test, fix bugs, add features, test, ...
I hope this is a high-level overview that will help you get started.
Don't be afraid that your classes are to simple at the start. You can always add functionality to them at a later stage when the rough program is running.

Handling large number of Swing components

I'm doing a favor for an engineer friend by making him a program that helps him with the scheduling of his factory's production. Each type of product is broken down to a set of steps (they share a lot of them, but there are a few differences).
The programming issue:
Each time a new production process is registered I display a number of checkboxes representing the before mentioned steps. He can choose which steps he needs added for this particular product. If he checks a checkbox, two (or more) textfields appear where he can add additional information (starting date, duration, comments, etc...). My problem is that this is a lot of individual components and I am unsure how to handle them. Since I will need to have access to all of them at some point (the checkboxes to see if that step is needed and all the textfields for the data) I was thinking of having them all as fields, but that doesn't feel right...
Another approach could be to make a container class that groups the textfields together with the checkbox. Something like this:
ArrayList<MyComponentGroup> group;
for (MyComponentGroup cg : group) {
if (cg.getCheckBox().isSelected()) {
//access and read the data from all the textfields in this object
}
}
What is the Java programming convention or the most commonly used method to handle this situation?
Here's what I would do when dealing with tons of components and similar requirements:
I would model the relationship between options (available through checkbox selections) and the related data to fill (requirements). This model may already be available for you.
I would attempt to use PropertyEditor instances and map them to model elements.
When the time comes to save or use the data filled by the user, I would just walk the model represented on the screen, grab the associated editors and deal with the value of those editors.
I think that the approach that I described above will give you less work and potentially and it will bring more flexibility for your friend.
You'd only pay the initial cost of getting the components relationships/dependencies in a nice model as well as registering the relevant PropertyEditors for visual editing.
One approach is to consistently give each JComponent a unique name. Use something hierarchical to fit the complex process, like "Whites.Rinsecycle.enableCB". For completeness, store this String as a clientProperty in the JComponent. Then you can use that as a key in a large Map to access all the components.
Maybe not the most "elegant" (I'd tend to go with a hierarchy of JPanels with relevant fields) but for a slightly quick and dirty, moderate sized project this is reasonable.

Designing a program with statistics

I am about to start my newest project, it is basicly an application that gets some data from a database and then display that data a graph!
now even though that this may seem simple it is important to me that this is done in a very correct way when it comes to object orientated programming.
Now my idea was the following:
I wanted to create the following four classes:
Adapter:
The class that connects the application to the database and recives the data
CallQueue:
This is an object that differences depending on what type of data is recived from the database and what type of data you wish to show on your graph. An example of this would be Cheese and fruits. both of them are food but they are very different types of food.
Statistics
This would be a tool class used to calculate the information recived from the database (for example changeing it to percentage instead of raw data)
Graph
This would be the class that gets the information from the statistic class and turns the numbers into a graph
GUI
This is ofcourse the GUI class where i will post the graph on!
Now i want to make the project as object orientated as possible. But my problem is that the information from the database is not always the same. For example if get the data from a day to day basis it will be different than from month to month. This means that the information is always going to change depending on what the user need.
How would i make this program object orientated ? and what type of connections should my classes have to eachother to make it most accessible. Do i have to create subclasses in order to simplify it?
should i add all information from the datbase directly into the CallQueue Class or should that object be created later on?
Update - Elaboration
The name callQueue is not a streaming implementation it is marely an object that should contain values of the data recived from the database (note that this is still in the idea phase and nothing is implemented). The idea is that a user opens the program and then chooses a day from and then a day to for instance: 04/11/2012 to 10/11/2012. The reason the objects value changes is when the day changes for instance to the following: 04/11/2012 - 04/12/2012 then a new graph will be created new information from the database will be calculated ect ect.
One thing that i am confused about aswell is the following:
When you have an object that is created from the database (adapater Note this could be optimized if you guys have a better idea) then how would you calculate statistics from that? would it be better that the statistic class called the adapter for data then worked with the data and then created the objects contain the calculated data?
Then the Graph class would need to get the objects data and insert into the graph.
From experience designing large systems and even smaller, the best approach is to think in terms of components rather than classes. This will allow you to break down your problems into smaller (and mostly independent) pieces.
So for example, you will have a component which sole responsibility will be to bring the data to your application for processing. That component will need to be able to deal with the multiple data sources, etc... That then becomes a sub-system that you can design independently from the rest of the application and deals with a specific problem, smaller than the whole.
If the sub-problems are still larger than they should, keep breaking them down into sub-compoennts, until the implementation of the components becomes almost trivial. At that point, you can start bringing in the notion of classes because you have enough visibility on the protagonists in your system.
In short, I put a lot of emphasis on separation of concerns. By isolating sub-problems into sub-components, you also isolate the solutions which makes it easier to correct your design mistakes or replace implementations without impacting the entire system.
Just my two cents...

How to go about display multiple "Menu" classes in java

Hi all I am relatively new to OOD and Java hence am not sure how to do this properly.
Currently I need to create an application (console/command prompt based) that involves going through a series of so called "menus" where the application will display your choices and you enter 1/2/3/4 etc. My professor told me to break up my boundary class (the class where all the display of choices is in) because it's too long (400+ lines).
Now comes the problem. If i were to break it up, I would have to keep creating new object classes to call on the different menu in different classes. For example:
Let say I have MainMenu, FoodMenu, DrinkMenu. So my main method will create a MainMenu object to call displayMenu(). From there, if I want to navigate to the food menu, I have to create another FoodMenu object and call displayMenu() under it again. Further along the codes, if i want to navigate back to the main menu, I would then again have to create the MainMenu object again and call displayMenu.
The above method would have so many variables waiting to be garbage collected and a total waste of memory. Is there another solution around this? Thank you very much in advance.
Hamlyn
Make all your menus either extend an abstract class (okay) or implement an interface (better), if you're not already doing that.
As for how to get to the menus, you can just store one of each type of menu in a menu array or some other collection (for example, a Map if you want to be able to look them up using a string or other object). Have that collection be globally accessible (static in some public class) and then you can display the same instance of a menu each time you need it.
First of all, garbage collection problems happen when you have thousands of objects floating around, not... three. So don't even worry about that.
But in general, your thesis that you need to recreate all those objects is flawed. You only need one of each, and they simply need to be able to get access to references to one another. For example, each "displayMenu" method might take a Menu as an argument; that displayMenu() method would set things up so that the "return to previous menu" option invokes the Menu that was passed as an argument.
As discussed in How to Use Actions, the Action class is a convenient way "to separate functionality and state from a component." This example creates a menu of recent files using instances of the RecentFile class. A similar class for each of your MainMenu, FoodMenu, DrinkMenu might be a way to encapsulate related menu items.

Need advice on proper class design

I am supposed to write a simple Cinema Booking System, which allows a customer to make reservations for movies.
The Cinema consists or different theatres, with different amount of seats, price and movie showtimes.
The user should be able to input his name and other credentials and then make reservations for 1 or more movies and seats.
When he is finished booking, the system should output a receipt, listing his name, the movie(s) the showtime(s) and reservation number.
I have tried to follow the OOP-principles as best to my current capabilities.
The classes I've set up would be the following:
CinemaBooking -> entrypoint into programm
Room -> receives its seating size via [row] [col]
Movie -> has movietitle, shwotime, the room and a price.
Customer -> shoud store any user info like name , email and phone and generate
booking number
I am a bit unsure on where to put the user-i/o in this case: Shoud it remain within CinemaBooking, or should i generate a seperate class which only does the I/O?
Or should I just move the whole I/O stuff to another class (e.g. the Customer Class)?
There are many advises to be given, I'll give only most important.
First, the main idea of OOP was to suit real world, so it's better to make your classes as close to real objects as possible.
Create class Booking which will be just equivalent of a ticket, not an entry point for a program. I.e. it will contain information about user, theatre, seat and cost.
Create class Theatre which will contain number of seats (not rows x cols - some seats may be reserved, some may be broken, and some theatres just haven't squared structure). Alternatively, since one Theatre can have several rooms, you can create class Room, which will have property "seats", and then add Rooms to Theatre.
Also create class Movie. Movies and Theates/Rooms will ref each other: Movie will contain list of Theatres it is showed in, and Theatre will have list of Movies it shows.
Then create class Seance, which will contain time and movie.
Create class Customer only in case you will work with this customer later and want to save his attributes (name, history of bookings, etc.). Otherwise it makes no sense to create one more class.
This is your model. Classes may very a bit, but if you got core idea, this won't be a problem.
Second, create class BookingSystem which will summarize functionality of all previous classes. It will be an implementation of Facade design pattern, and it really simplifies access to your booking subsystem.
Third, create separate class for I/O work. Never put I/O work to the model classes. Imagine, that your cinema booking system will be the part of another system with it's own I/O - you will need to redesign all your code to receive data from higher layers. So, just make separate class for user's input and program's output.
And this will be your view.
Finally, create main program class. You can give it same name the program have itself of something like that. This one will just control program flow from view to models and back. So, this part is called controller, and overall idea is known as Model-View-Controller pattern.
Whenever I make class, it has following in it:-
All instance variables set to private.
Implement getters and setters.
Implement toString() method.
If you are using Eclipse then it will help you to implement these methods automatically. Just write instance variables, right click in editor -> Source -> Generate getters and setters.
Write toString() methods on all the classes. Worry about the I/O later. Get the relationships right first. I/O is the least of your worries.
Actually, ticket will not contain info about user theatre seat or cost. It will contain references to other objects: User, Theater, Seat Cost.
You will need o0ne "manager" type class that will hold the rest of the program: BookingApp which has a main() could be it. I agree don't worry so much about interface for now - but DO NOT print to the terminal from Domain classes. Use toString() to test the object content, but the main() method should call getters on the other classes and create the output.
Very bad idea and form to have domain classes writing directly to the UI.
So, you have Theatre, User, Seat, Ticket, Price. Consider dependencies. Seat is tied to theatre and price is based on theatre and seat, I assume.
Start with the Things, and draw lines between them to show how they will communicate or reference each other. For example, given a User, find all their tickets - from ticket find seat and from seat find theatre.
Then add the attributes (private as JavaGeek said).
Start small. Maybe just Theatres and Seats. Get that to work then add the next class. Add to your design incrementally and iteratively. DO NOT try and write and compile the whole thing at once.
I suggest Peter Coad's Java Design book ( very cheap and very good) as a good intro to java design.

Categories