I'm developing a game in Java which I can only describe as a variant of The Sims.
The main interface for the game consists of a level and will have a large variety of furniture which can be placed on the map. My problem is that whilst I can think of ways to construct a system which will allow me to assign properties to each item of furniture, I want to make sure I do it the correct way before I head down a long path to completing it. For example, if I referenced an object with an identifier of "sofa", the furniture object's members could be accessed through searching through all available objects and finding the one with the matching identifier.
My method would be to make a very large .java file with instances from a base furniture class for each item of furniture, with each one having an identifier and all its different properties assigned, such as image, position, rotation etc, plus their own unique code for each different function they provide (eg. sitting, sleeping).
For saving/storing these objects in a text file, I would just store the name of the identifier in the string array in the text file and when loading, I could just create the object by instantiating the object the identifier points to.
Would I be correct in using most of these methods, or are better ones available? If you've found it a struggle to comprehend what I've written (and I had trouble writing it clearly), then a more simple question would be:
How are items of furniture managed in The Sims with respect to the sheer amount available and the many different variations/rotations they can be placed in (and stored/saved)?
I think what you need to do here is try and abstract as much of the common functionality to the base classes and then each item should extend as necessary.
Eg
A Sofa... Seat extends Furniture extends Object
A Office chair would be the same
A DiningTable would be different tho... Table extends Furniture extends Object
You will also want various Interfaces so that a Sofa implements Sittable think of the functionailty that might be common to different objects, like they might all be Placeable
Also for saving and loading you might want to make your objects serializable.
Read up on Abstraction, Interfaces and Serialization
Component-Entity-System may be a good thing for you to look into. It's basically what you're describing. There's a large collection of entities, each entity has a collection of Components, and there are systems which know what to do with certain components.
EG: A piece of furniture is an entity named "chair". It has many components, one of them is "Renderable". And your game loop passes all renderables into the "renderer" System which calls the Renderable.render() method.
Note, this isn't very object oriented, but I find it's tough to design games like this in an OO way because the object hierarchies explode. Everything has some things in common with everything else. You'd end up with generic classes like "Unit" and "Thing" which isn't very OO either.
Related
I am currently creating a dungeon crawler. I handle all of the dungeon generation, collision box generation, treasures and enemy generation, and player generation in one class called Dungeon. Each of the objects created in the dungeon class has a getter.
In the Main class, I am using an animation timer to handle all of the updates from the player moving, opening treasures, etc. This requires access to many of the objects created in the Dungeon class.
I am trying to better understand the use and benefit of object references in Java. My question is: What is the more efficient method to access the variables in the Dungeon class (or any other class for that matter) since I am accessing them hundreds or thousands of times?
For example, all of the treasures in the dungeon are in an ArrayList variable that is a member variable of the Dungeon class. So, I can retrieve that array list in my Main class like this: dungeon.getTreasureList(). If I need to get a specific item in that ArrayList I could use: dungeon.getTreasureList().get(i) where i is the index of the treasure object I want. This is fine for short calls (organizationally speaking) but it gets really messy with longer calls like so: dungeon.getPlayer().topIntersects(dungeon.getCollisions().getWalls())
Alternatively, I could create a reference to the treasureList in my Main like this: ArrayList<Treasure> treasure = dungeon.getTreasureList(). Then, if I need a specific object in the ArrayList I can call: treasure.get(i). This can clean up the long call above to something more like this: player.topIntersects(collisions.getWalls());. This is much easier to read and, as a result, I favor this method a bit more.
Disregarding the organizational benefits, is it a better practice to create a reference to access a variable to access information, or use the longer form and getters (like thisdungeon.getTreasureList().get(i))?
It would seem, that by creating a reference for player and collisions in the call dungeon.getPlayer().topIntersects(dungeon.getCollisions().getWalls()) I am saving two function calls by using player.topIntersects(collisions.getWalls());. Namely, one function call to dungeon.getPlayer()and one call to dungeon.getCollisions().
Since this is being called thousands of times while the game is running, it seems safe to assume I am saving many thousand function calls to dungeon.getPlayer()and dungeon.getCollisions(), resulting in a more efficient code. Am I right in this assumption?
EDIT: Trying to make the question more objective and less opinion based and corrected misleading phrasing
My opinion is that this question will be closed soon, because it's too opinion-based.
But if I did offer my opinion I'd say that letting classes access private collections and then operating with them is poor encapsulation.
Better to hide those details and provide methods to give the information you want without giving away the private details.
We have an application that is composed of a number of independent components and sub-systems. We are looking at implementing a simple event logging mechanism where these components & sub-systems can log some events of interest. Events could be something like
New account created
Flight arrived
Weekly report dispatched to management etc.
As you can see, the event types are heterogeneous in nature and the attributes that needs to be logged differs based on the event types. New account created event, for example, will also log the account-id, the name of the user who created the new account etc. Whereas, the flight arrived event will be logging the flight number, arrived at, arrived from etc.
I'm wondering what is the good way of modelling the event types and the attributes.
One option is to do it object oriented way - to have an AbstractEvent that will have some common attributes (timestamp, message etc) and then create a full hierarchy of classes underneath. The flight events, for example, can look like
abstract class AbstractEvent;
abstract class FlightEvent extends AbstractEvent;
class FlightArrivedEvent extends FlightEvent;
class FlightCancelledEvent extends FlightEvent;
The problem I see with this approch is that we have hundreds of events which will result in class explosion. Also, whenever we add a new event (very likely), we have to create a class and distribute the new package to all the components and sub-systems.
The second option I can think of is on the other end of the spectrum. Have a simple Event class that contains the basic attributes and wrap a map inside it so that the clients can populate any data they want. The code in that case will look something like this.
class Event {
private timestamp;
private eventType;
private Map attributes;
public Event ( String eventType ) {
timestamp = System.nanoTime();
this.eventType = eventType;
attributes = new HashMap();
}
public Event add ( String key, String value ) {
attributes.put ( key, value );
return this;
}
}
//Client code.
Event e = new Event("FlightEvent:FlightArrived")
.add("FLIGHT_NUMBER", "ABC123")
.add("ARRIVED_AT", "12:34");
While this is flexible, it suffers from inconsitency. Two components can log the FLIGHT_NUMBER key in two different formats (FLIGHT_NUMBER & FLGT_NO) and I can't think of a good way to enforce some convention.
Any one have some suggestions that can provide a nice compromise between these two extreme options?
There is a Java event framework (see java.util.EventObject and the Beans framework) but the fundamental question you are asking is not connected with events. It is a design question, and it is this: do I use Java classes in my application to represent classes in my business domain?
It is clear that the different types of event are different "classes" of thing, but for maintainability reasons you are considering representing your business data in a map so that you don't have to write and distribute an actual class. If you take this to a logical extreme, you could design your whole application with no classes and just use maps and name-value pairs for everything - not just events. It would be a mess and you would be debugging it forever because you would have no type-safety whatsoever. The only way of finding what was in map would be to look up in some documentation somewhere what someone might have added to it and what type that object might be.
So, here is the thing - you would not have actually have gotten rid of your class definition.
You will have moved it into a Word document somewhere that people will have to refer to in order to understand what is in your map. The Word document will need to be maintained, verified and distributed but unlike the Java class, it won't be checked by the compiler and there is no guarantee that the programmers will interpret it correctly.
So I would say, if there is a class, put it in your code and then focus on solving the problems of distributing and versioning the Java classes instead of distributing and versioning Word documents.
I will mention versioning again as this is an issue if you might serialise the objects and restore them, so you need to think about that.
Some caveats:
If you are writing a piece of middleware software that routes events from one system to another system, it might be you don't need to know are care what the data is, and it might make sense to use a generic holder in this case. If you don't need to look at the data, you don't need a class for it.
You might get complaints from high-level designers and architects about the number of classes and the work they have to do in defining them compared with a map and name/value stuff. This is because putting classes (i.e., the real design) in Java is harder than putting them in a Word document. Easier, if you are high-level hand-waving type guy, to write something wishy-washy in Word that doesn't need to run or even compile and then give the real design work to the programmers to get working.
Can [someone] provide a nice compromise between these two extreme options?
No. There is no generic one-size-fits-all answer to this problem. You will have to find yourself a balance which fits the general design of your product. If you nail everything down, you will need thousands of classes. If you give a lot of leeway, you can get away with a few but you're paying your freedom with precision. See my blog post "Designing a Garbage Bin"
Do you have shared attributes? As in: Do you expect to define attributes of events like you define classes right now with very tight-fitting semantics?
That would mean you have a simple event and typed attributes (i.e. String value simply isn't sufficient). You need formatting and validation for attributes or ... attributes themselves need to be classes.
If this is the case, you can use my type-safe map pattern: http://blog.pdark.de/2010/05/28/type-safe-object-map/
Event type "explosion" is not a problem. In fact it is a desirable approach as it allows the components to be independent of one another. I wouldn't necessarily make all events inherit from a single superclass unless it gives you a lot of reusable code because it can cause dependencies to start proliferating.
I would put the event types in a separate project that will be a dependency of both the publisher and consumer.
What is your communication mechanism for these events between components? JMS? If so you could also consider making your messages XML and using JAXB.
I would definitely discount the map approach as it destroys any hope of polymorphism or any other oo niceties.
I am new to Object Oriented Programming. I am developing a software for a Grocery Store. The Grocery Store has Customers, Customers has Address and Subscriptions. All these are different classes in the application.
I am little confused, that in which class should I create which method and how I should decide this.
Like
viewSubscription() should be a part of Subscription class or Customer class.
modifyCustomer() should be a part of Customer class or Store class.
Methods are behavior, variables are state.
What can a subscription? from what is a suscription made?
A Suscription cant view itself, who will view a subscription? a customer?
A suscription should be a class indeed, but a POJO, its a collection of states. And customers can see those states.
One of the ideas of object oriented programming is to group things together that make sense. In your example, since they are dealing with information related to the Customer, I would probably place both methods in the Customer class.
OOP makes it easy to break down complex problems. You might want to sit down and do a schema of the relations between your classes and what data your classes will contain. It will become obvious where which method should go.
Why should view subscription should a member of Subscription?
Always ask your self this simple question: view subscriptions of what? On what do you want to do the action.
I bet you want to view the subscription of a Customer! Make viewSubscription a method of Customer! customer1.viewSubscription()
Check out UML and OCL. They will help you to model your ideas.
Just an overview: An object represents a real life entity lets say for example a car, A car has some properties like it has wheels,a steering,a gearbox and much more, the same way it has some behaviors like it moves forward, steers left, steers right and it stops.
All the things mentioned above related to the car when brought down to an Object oriented programming approach will look like, We make a class Car and the properties(wheels,a steering,a gearbox etc) are defined as variables inside that class and the behaviors(moves forward, steers left, steers right) are defined as functions in that class.There's no hard and fast rule relating OOP you just have to make it feel logically as Real Life as possible for instance in your case the Subscription Class has all the information related to the subscription and the Customer has a subscription so the viewSubscription()method should come inside Customer Class as a Private field because it should fetch and display the subscription information related to a particular customer. modifyCustomer() as it involves modifying the data fields of the Customer class so this too will come inside the customer class as all the modification of the field values should probably be done inside the class containing the fields.
I'm using an API providing access to a special server environment. This API has a wide range of Data objects you can retrieve from it. For Example APICar
Now I'd like to have "my own" data object (MyCar) containing all information of that data object but i'd like to either leave out some properties, augment it, or simply rename some of them.
This is because i need those data objects in a JSON driven client application. So when someone changes the API mentioned above and changes names of properties my client application will break immediatly.
My question is:
Is there a best practice or a design pattern to copy objects like this? Like when you have one Object and want to transfer it into another object of another class? I've seen something like that in eclipse called "AdapterFactory" and was wondering if it's wide used thing.
To make it more clear: I have ObjectA and i need ObjectB. ObjectA comes from the API and its class can change frequently. I need a method or an Object or a Class somewhere which is capable of turning an ObjectA into ObjectB.
I think you are looking for Design Pattern Adapter
It's really just wrapping an instance of class A in an instance of class B, to provide a different way of using it / different type.
"I think" because you mention copying issues, so it may not be as much a class/type thing as a persistence / transmission thing.
Depending on your situation you may also be interested in dynamic proxying, but that's a Java feature.
I'm designing a game, but I can't quite get my head around the inheritance structure. I'm normally fairly good at it, but this one just has too much overlap and I can't decide on it all.
I'm seeking to model sailing vessels - think the Age of Sail. Presumably therefore everything extends a Vessel class.
There are then several types of vessel style: rowed (galleys, canoes), square-rig, fore-and-aft rig, with different behaviour. Each of these is further subdivided into several other types. I can't decide whether this should be a series of interfaces or extensions of Vessel. Note also that there can be some cross over (a vessel can be both rowed and square rigged) which leads me to think interfaces?
Ships also have different behaviours: merchant vessels, men of war, privateer, pirates. I really can't work out whether this should be an interface or an extension of another class. There is no crossover of type in this case, however.
Finally there are several behaviours which individual ships can have. Merchants may be in a convoy (defend themselves) or independent (run away). Men of war almost always attack unless heavily outgunned... but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs. I'm assuming that this should be an interface too?
My big problem is that each style of ship (frigate, battleship etc) can fulfil almost any of these roles, so I can't build a simple solid inheritance structure. Frigate can't extend man-o-war because some are privateers. Sloop can't extend square rigged because some are fore and aft rigged. etcetc.
Any thoughts would be appreciated, I'm at a bit of a loose end.
Thanks
Make the "behavior" part as interfaces. That will help you assigning different behaviors to different ships without problem. Strategy Pattern is helpful here. In a nutshell, it states that the changeable and the constant properties should be separated.
For different means of movements, composition sounds like the most suitable answer at this moment.
Regarding the "but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs." part, I guess this has nothing to do with the inheritance tree. You can make "groups" of classes depending up on your need.
This might help you:
"There are then several types of vessel style:..." is specifying different possible behaviors. So "Movable" interface and its subclasses are for that. In the "Vessel" class, you can have a member of type "Movable". Since "Movable" is an interface, any class which implements it, is assignable to this member. So any subclass of Vessel can have any possible behavior, which we cna change at runtime as well. You can also make it an ArrayList. (Not sure if you actually want to do it or not). But if you need multiple different behaviors for a same vessel, you can do it.
When you say "Ships also have different behaviours:..." it feels like separate classes extending Vessel will satisfy this requirement. The sentence "There is no crossover of type in this case, however." makes life easier.
For the nest para "Finally there are several behaviours which individual ships can have...", you should add one more member for different possible behaviors. It will mostly be an ArrayList as one vessel will have multiple attack modes.
Fro the last para, if you can give some more details, I may be able to give some more ideas.
Ok, here are some ideas:
Vessels have one or more means of propulsion (oars, sails, etc.), which you can model by composition (e.g. have a list of propulsion methods).
Vessels use one of a variety of strategies (use the strategy pattern -- see http://en.wikipedia.org/wiki/Strategy_pattern -- for this)
Strategies which depend on the presence of other nearby ships will need some way of querying for those other ships -- so you'll need some sort of data structure that allows you to find which objects are near which other objects (look into the sort of data structures that are used for broad-phase collision detection)
As an alternative to the strategy pattern, you could switch to using a component-based design. In this setup, a vessel would be composed of one or more propulsion components, a strategy component, etc. You could then combine individual components as you see fit to make different vessels.
As an extra bonus, component-based designs are very helpful if you want your game to be data-driven, because you can just write a saver/loader for each different type of component, rather than for each possible type of vessel.
You might want to see here if you're interested in this sort of approach:
http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
I want to provide a bit of advice based on the second paragraph of Bhusan's answer, which I quote here in full:
"Regarding the "but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs." part, I guess this has nothing to do with the inheritance tree. You can make "groups" of classes depending up on your need."
This leads me to believe that you additionally may want to consider the Composite pattern for certain groups of ships, at least those that are comprised of ships that all share the same behavior. See http://en.wikipedia.org/wiki/Composite_pattern where it is written that "the composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object."
For instance you say "Merchants may be in a convoy (defend themselves)", but presumably they can defend themselves individually as well? This is all easier said than done of course, and my advice to you is to not over-think it and start with a very small subset of what you want to do as a protoype
You should separate the types and use the strategy pattern.
Immutable properties should be bound to the inheritance tree (e.g. a frigate won't turn into canoe, these are exact, non-behavioral types, inheriting from vessel) and everything that may change should be stored as references to behavioral types which are intrachangable. (Man-o-war is a behavioral type)
AI should be handled separately, for instance with states, but that is also have to be in a different module in your architecture.
Instead of thinking about it as strictly inheritance, I think you need to think about object Composition and how that can help make things easier.
For example: a Ship has a Behaviour. (Composition... the ship delegates to the behaviour to determine how to react to X situation)
A Pirate is a Behaviour (Inheritance from a Behaviour interface)...
You should not extend the Vessel class. Rather, a Vessel object should contain other objects that describe it. (This is known as Dependency Injection, to be annoyingly pedantic--forget I said that.) You have a Propulsion class, with instances for square-sails, fore-and-aft, and oars. You might want special instances of each for big and small hulls. You have a Behavior class to handle their attitude. Sometimes a simple integer works as well as a class. Your Armament class could be, instead, just a number of guns. (Or two numbers, one for poundage.) If you expect to ram, or have a ship loaded with rockets, or need to distinguish between long guns and carronades, you might need to go back to using the a class.
This lets you switch characteristics on the fly if you want--though you probably don't. Still, you can go from sail to using sweeps, or switch bold ship-of-the-line behavior with save-the-cargo behavior of a merchant to implement a captain losing his nerve. Anyway, it's there if you need it.