Using Object Pools in Libgdx - java

I'm creating an android game that uses an Entity object class that is then extended in many different types (i.e. enemies, bullets, etc). Is there a way to create a pool of type Entity and then transform the obtained Entity objects into whatever I need at runtime (say a bullet type)? Passing the entity as an argument to a constructor will just defeat the purpose of the pool correct? An example is below:
public class EntityPool extends Pool<Entity> {
public EntityPool (int initialCapacity, int max) {
super(initialCapacity, max);
}
protected PooledEntity newObject () {
return new PooledEntity();
}
public Entity obtain (int objectType) {
Entity ent = super.obtain();
if (objectType==SOME_OBJECT_TYPE)
//Do something to make ent into that object type
return ent;
}
public class PooledEntity extends Entity {
PooledEntity () {
super(null, 0, 0);
}
public void free () {
EntityPool.this.free(this);
}
}
}

The point of an object pool is generally to avoid system allocation and deallocation overheads and requires you know a "worst case" limit on the number of each type of entity you will want to allocate. So, assuming your entities are rather different in lifetime and usage, you probably want to have separate pools for each entity. (You can definitely improve the pool as in #zaske's answer.)
On the other hand, if you really want a single Entity pool, and you want to customize those entities at run-time, you could change from using Entity subclasses to something like:
class Entity {
EntityCustomizer custom;
...
}
Then when fetching an Entity out of the pool you pass in a Bullet or Ship or whatever customizer object:
public Entity obtain (int objectType) {
Entity ent = super.obtain();
if (objectType==SOME_OBJECT_TYPE)
ent.custom = EntityCustomizer.SOME_OBJECT_TYPE_IMPL;
return ent;
}
(I'm pretty sure this is a well-known pattern and I should be using the appropriate language to identify the parts ...)
All said, I think separate pools for each Entity type are the way to go, as my work-around is pretty hacky (you're trading a bunch of compile-time type checking for some run-time flexibility).

With your current code, your pool can store any object that is an Entity or of a sub class of entity. As a result, you can only use instanceof, or downcast to get the type of the concrete object.
If you would like to have different Pools per type, you can consider changing the declaration of the pool to :
public class EntityPool<T> extends Pool<T extends Entity>
And then for example have:
EntityPool<Bullet> bulletsPool = new EntityPool<Bullet>(); //only objects of Bullet of sub classes can be added

Related

Pattern to break up external API calls?

I am trying to wrap my mind around how I would go about implementing this specific problem. We have an external API that performs some logic and returns back the result of that logic. Unfortunately, the API returns a new object as the result as opposed to just the part that I am interested in. For example, the code would look something like this:
public class ComplexObject {
//lots of fields
}
public interface LogicApplier {
LogicResult applyLogic(ComplexObject obj);
}
public class LogicResult {
ComplexObject result;
public ComplexObject getResult();
}
public class FirstImplementation {
private LogicApplier _applier;
public Implementation(LogicApplier applier) {
_applier = applier;
}
public ComplexObject mainImplementation (ComplexObject apply) {
LogicResult logicResult = _applier.applyLogic(apply);
ComplexObject newComplexObject = logicResult.getResult();
//Do some other stuff with new ComplexObject
}
}
So question is: what would be the best way to put a limit on LogicApplier's "power" over FirstImplementation? For example, our motivation to call logic in the first place is to derive a missing field, let's say "name". This field could potentially be different in, say, SecondImplementation where that implementation is now looking to derive "street address" from LogicApplier API. However, there is nothing to stop LogicApplier from changing some other field, say "idNumber".
Is this best solved by a adding an interface for our specific implementations and manually mapping fields? Something like:
public interface SecondImplementationLogicApplier {
public String deriveAddress(ComplexObject o);
}
public class LimitedImplementationLogicApplier implements FirstImplementationLogicApplier, SecondImplementationLogicApplier {
LogicApplier _applier;
public LimitedImplementationLogicApplier(LogicApplier applier) {
_applier = applier;
}
public String deriveFirstName(ComplexObject o) {
LogicResult res = _applier.applyLogic(o);
return res.firstName;
}
public String deriveFirstName(ComplexObject o) {
LogicResult res = _applier.applyLogic(o);
return res.address;
}
}
I think you are on right track with your LimitedImplementationLogicApplier. You should guard objects in your domain from possible corruption from the outside. Only update fields that you need.
It looks like your ComplexObject is mutable. I'd consider hiding it behind the immutable interface (that don't have any setters or way to change the object exposed) and pass immutable interface into your LimitedImplementationLogicApplier so its got no chance of mutating ComplexObject.
If your API requires ComplexObject type and you can't change that, to prevent mutation you could:
Option 1
Create a clone of your base ComplexObject instance and pass it into the API. After you've got the result back, you update the needed fields on untouched base instance. This will work nicely if ComplexObject is "thing in itself" and changes in its state does not have side effects outside of the class instance, like changing databases or affecting other state.
If mutation of ComplexObject has side effects or may have them in future then its a real trouble.
Option 2
Inherit a ReadonlyComplexObject class from ComplexObject and pass that into the API. In ReadonlyComplexObject you will suppress all the behavior of the parent to prevent modification.
This is hacky in my opinion and will create more work later - if ComplexObject will be extended with new properties later you will need to make changes to ReadonlyComplexObject otherwise mutation will still occur.

Java Method return concrete type from generic return type

I am trying to make an enum list, and have an abstract method defined in the enum, which each enum value implements. The problem I am facing is that the abstract class has a generic return type but I want each enum value to return a concrete type.
I'll give an example:
public enum Attributes {
name {
#Override
public void createAttribute(Person person) {
//Do some validations
//Save in some storage
}
#Override
public Name getAttribute(Person person) {
// Validations
// Retreive from storage
return new Name("test");
}
},
address {
#Override
public void createAttribute(Person person) {
//Do some validations
//Save in some storage
}
#Override
public Address getAttribute(Person person) {
// Validations
// Retreive from storage
return new Name("test");
}
}
public abstract Object getAttribute(Person person);
public abstract void createAttribute(Person person);
}
Here the issue is that I would need to do typecasting to get the concrete object which is not recommended and I don't get any type of safety. How Should I go about so that using the enum value I can get my concrete object instead of the generic one.
Now I wanna call this as,
Arrays.stream(Attributes.values()).forEach(r -> {
r.createAttribute(person);
}
final Address address = Attributes.address.getAttribute(person);
final Name name = Attributes.name.getAttribute(person);
So now whenever I need to add a new attribute I don't want to write create methods for it in the Person class every time. I just add it to enum and it gets created. But now since I have the create method in the enum, I also want the getAttribute to be present here.
Here the issue is that I would need to do typecasting to get the concrete object which is not recommended and I don't get any type of safety.
You're right. Given an enum type E with an associated enum constant C, the type of the expression E.C is E. Java provides no mechanism for naming or representing a narrower type for that expression. One of the implications is that although an enum instance can implement methods with covariant return types, the covariance is not visible outside the instance. If you depend for some purpose on the narrower return type of one of those instances' methods, then casting is your only alternative.
And you're right that such casts are not type safe. They cannot be checked by the compiler, and in practice, you as programmer can get them wrong. But the information to perform a compile-time check is not expressed by the language, so there is no scope for a workaround in the language as it is defined today.
How Should I go about so that using the enum value I can get my concrete object instead of the generic one.
You should choose an altogether different approach, not involving an enum.
If you stuck with the enum then you would have to adopt an approach that relies on the enum instances to perform any tasks that depend on their own particular characteristics. Because you ask so persistently, one possibility would be to implement a variation on double dispatch. Instead of a getObject() method, you would have something like
void acceptReceiver(AttributeReceiver r, Person p);
paired with
public interface AttributeReceiver {
default void receiveName(Name name) { /* empty */ }
default void receiveAddress(Address addr) { /* empty */ }
}
Of course, the enum instances would have to implement acceptReceiver appropriately.
You would probably want to use that a little more directly than just to retrieve attributes, but you could use it to retrieve attributes something like this:
class Example {
Name name;
Address address;
void retrieveAttributes(Person person) {
AttributeReceiver receiver = new AttributeReceiver() {
public void receiveName(Name n) { name = n; }
public void receiveAddress(Address a) { addr = a; }
};
Attributes.name.acceptReceiver(receiver, person);
Attributes.address.acceptReceiver(receiver, person);
}
}
But that's awfully roundabout when you have the alternative of using (just) methods, whether on Person or even on some non-enum utility class. I continue not to see any advantage to involving an enum here. I think your code overall would be more complex and harder to understand and maintain with enums than without.
The root issue is that you are abstracting away details that you actually care about. That's a deep design flaw. You can program your way around it, but it would be better to choose a more appropriate level of abstraction in the first place.

Creating child objects on basis created parent object in java

I'm learning java design patterns and I wonder if I can apply some with following problem. I have class Solider and some child classes, for example: General and Sergeant. I'm creating Solider object and in runtime I want to change this object to General or Sergeant object, or create new Sergeant or General object using created earlier Solider object:
Solider s = new Solider(...);
.....
if (generalCondition) {
General g = createGeneralFromSolider(s);
//or better:
//General g = promoteSoliderToGeneral(s);
} else if (sergeantCondition) {
Sergeant sr = createSergeantFromSolider(s);
//or better:
//Sergeant sr = promoteSoliderToSergeant(s);
}
Firstly I decided to create additional constructor in General/Sergeant Class:
Class General extends Solider {
General(Solider s, Map<String, String> generalSpecificParams) {
//first we are going to copy all solider params to general params (bad idea if we have a lot of params)
this.setParamX(s.getParamX());
....
//then we can assign the rest of general-specific params
this.setGeneralSpecificParams(generalSpecificParams);
}
}
and use it in methods createGeneralFromSolider but I'm not sure if it is elegant way. Main disadvantage is that I create new object, so after calling createGeneralFromSolider I have 2 object in memory. I would rather have one object in memory: General/Sergeant promoted from Solider (object General/Sergeant which earlier was the Solider object). I wonder if I can use some design patter to resolve it. I remember that in C++ there has been something like copying constructors which copying all params from one object to another by assigning all params, one after another. In Java I didn't hear about anything similar.
You would probably need to use a Factory pattern for this kind of situation.
For example:
public class SoldierFactory {
//use getSoldier method to get object of type Soldier
public Soldier getSoldier(String soldierType){
if(soldierType == null){
return null;
}
if(soldierType.equals("case1")){
return new General();
} else if(soldierType.equals("case2")){
return new Sergeant();
} else if(.....
}
return null;
}
}
public class FactoryPatternDemo {
public static void main(String[] args) {
SoldierFactory soldierFactory = new SoldierFactory();
Soldier s1 = soldierFactory.getsoldier("case1");
}
}
I think its better to not create the Soldier ahead of calling Soldier factory. You're going to change it regardless during run-time right?
First of all, when constructing child classes, use super as the first statement of the constructor like so:
class Soldier {
private String rank; // e.g. Pvt, PFC, etc.
private int yearsOfService;
// ... (Standard constructor)
public Soldier(Soldier s) {
this.rank = s.rank; this.yearsOfService = s.yearsOfService;
}
// ... (Getters and Setters)
}
class Sergeant extends Soldier {
private int subordinates;
public Sergeant(Soldier s) {
super(s)
this.rank = "Sergeant"; // overwrites this Sergeant's rank
this.subordinates = 0;
}
}
You could easily encapsulate this in a promoteSoldierToSergeant method. However, this can lead to telescoping constructors if classes with many attributes are designed naively, or necessitate your map-based workaround. To resolve this, I'm personally a big fan of the Builder pattern, but you can also consider the Factory pattern.
Your question regarding "copying constructors" is perhaps best addressed by reading up on the Clonable interface, but be aware of the differences between shallow and deep copies, and the implications for your classes and data structures.
I think your approach is totally acceptable. If you have an object X, that you want to turn into Y, you can do it in Y constructor, copying all necessary fields.
You could as well use a builder, or static factory methods, but either way you'll have to copy fields, as there's no automatic copy constructor in java (except if you use some dedicated library such as lombok, which can provide full-args constructors from annotations)
You worry about having 2 objects in memory. But if you remove every reference of the original Soldier, the garbage collector will destroy it.
Last thing, as mentionned by #tsolakp , is it a good design to have General inheriting from Soldier? Couldn't it be just a "grade" variable, or something like that, to reflect this state? It's a common mistake to overuse inheritance where composition would be sufficient, and would cause less troubles.
What you want could be achieved using Reflections.
That way you can automatically copy fields from the instance of parent to child class.
Your code would look something like this:
public static void copyObject(Object src, Object dest)
throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException, SecurityException {
for (Field field : src.getClass().getFields()) {
dest.getClass().getField(field.getName()).set(dest, field.get(src));
}
}
public static General createGeneral (Solider solider, String devision) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
General general = new General();
copyObject(solider, general);
general.setDevision(devision);
return general;
}
The Field import is java.lang.reflect.Field;
========================================================================
Another way would be to use the Apache Bean Utils.
Than, you can use it's cloneBean(Object Bean) method like this:
General general = cloneBean(solider);
to copy the fields from solider to general and after that all the fields that are specific to child class (General).
========================================================================
EDIT: It would also be wise to introduce another child class that would be used for "ordinary" soliders if you intended to use the parent class Solider for "ordinary" soliders (which I suppose you do according to your commented method name promoteSoliderToGeneral(Solider s).
So, for example you would have a parent class called MilitaryMan and 3 child classes that extend it: Solider, General and Sergeant.
This way, you can uniformly handle all of the MilitaryMan. And, you can check if the MilitaryMan is a Solider, General or Sergeant with:
if (militaryMan instanceOf Solider) {
// do solider specific processing
...
} else if (militaryMan instanceof General) {
...
} else if (militaryMan instanceof Sergeant) {
...
}
I think it would be cleaner this way.

How do Generics and Fields assist DAO Pattern in Standalone Java applications

//Interface DAO
public abstract class BaseDAO<T extends BaseDTO> {
public void update(T t) throws DBException {
Field[] fieldsToInsert = t.getClass().getDeclaredFields();
//code to update database object academic or event
}
public Integer create(T t) throws DBException {
Field[] fieldsToInsert = t.getClass().getDeclaredFields();
//code to create academic or event in database
}
}
//Concrete DAOs
public class AcademicDAO extends BaseDAO<AcademicDTO> {
//provide implementation
}
public class EventDAO extends BaseDAO<EventDTO> {
//provide implementation
}
//Transfer object
public class AcademicDTO extends BaseDTO {
String title;
String surname;
//getters and setters
}
public class BaseDTO {
protected Integer ID;
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
}
Hello Guys, I have a sample code on me that follows the above structure to create a small java application to manage academics and events. It is leniently following this pattern
1- You experts are familiar with this pattern more than me. I would like to understand why generics are used in this case so DAOs can extend and implement a generic base class. It would be great if one can show how generics here may be advantageous using an example.
2 - I have also witnessed the use of java Fields. Is there a link between generics and Fields?
I would like to document DAO pattern in an academic report, but I am finding difficult to understand how Generics and Reflect Field play a part here. Do they support flexibility and loose coupling?
The code you've provided is reusable set of logic to load and persist entities. Many times, in an application of non-trivial size, you'll wind up persisting many different types of objects. In this example, you can define as many objects as necessary, but only define the logic to actually save and load once. By asking the DTO what Field objects are there, it can get at the data to help construct queries for loading and saving.
Generics allow you to use this pattern while maintaining type safety. AcademicDAO can only handle AcadmeicDTO. You can't use AcademicDAO to store EventDTO. Generics allow the instance of the class to rely on a more specific type when dealing with the Field objects. If you didn't have generics, the BaseDAO would take Object, and you wouldn't be able to access any methods except those that Object provides because the JVM wouldn't know what class is provided, so it has to limit it's knowledge to that of Object. Using getClass().getDeclaredFields() bypasses that limitation because getClass() returns the actual class of the Object parameter.
Field is just a way to use reflection to access the values of the properties in each DTO. If you had to access the fields directly, with getTitle(), you couldn't reuse a generic base class to do your persistence. What would happen when you needed to access EventDTO? You would have to provide logic for that. Field allows you to skip that logic.
Edit:
To explain what I mean by accessing getID, you could do the following within BaseDAO because T is known to be a BaseDTO with a getID() method defined:
public abstract class BaseDAO<T extends BaseDTO> {
public boolean update(T t) throws DBException {
Integer id = t.getID();
Field[] fields = t.getClass().getDeclaredFields();
// Assuming you have a db object to execute queries using bind variables:
boolean success = db.execute("UPDATE table SET ... WHERE id = ?", id.intValue());
return success;
}
}
If you had this instead (in a non-generic class):
public boolean update(Object o) throws DBException {
// This line doesn't work, since Object doesn't have a getID() method.
Integer id = t.getID();
Field[] fields = o.getClass().getDeclaredFields();
boolean success = db.execute("UPDATE table SET ... WHERE id = ?", id.intValue());
return success;
}
You'd have to look through those Field objects, or ask for the ID field and assume it existed.
For question 1. The use of generics allows the same implementations of update and create to be used regardless of the type of the DTO. Consider if you didn't use generics. Then the best you could do for the parameter type of update would be BaseDTO, but then you could call
academicDAO.update( eventDTO )
which doesn't make sense. With the code as you have it, this would be a type error. So the main advantage is: better type checking.
For question 2. The use of Fields allows a single implementation of update and create to work on DTO object of various concrete types.

Java: Trouble with Generics & Collection type detection

I have a class called DataSet with various constructors, each specifying a different type of variable. It might look a bit like this:
public class DataSet
{
private HashSet Data;
public DataSet( DataObject obj )
{
Data = new <DataObject>HashSet();
Data.add( obj );
}
public DataSet( ObjectRelationship rel )
{
Data = new <ObjectRelationship>HashSet();
Data.add( rel );
}
// etc.
Note: I haven't yet gotten to test that code due to incomplete parts (which I'm building right now).
In a function that I'm currently building, getDataObjects(), I need to return all DataObject objects that this set represents. In the case of constructors that initiate the class's HashSet, Data with types other than DataObject (such as the above ObjectRelationship), there obviously won't be any DataObjects stored within. In this case, I need to be able to detect the type that the HashSet 'Data' was initiated with (like, to tell if it's 'ObjectRelationship' or not, I mean). How do I do this?
tl;dr: How do I tell the type that a Collection (in this case, a HashSet) was initiated with in my code (like with an 'if' or 'switch' statement or something)?
Sounds like you want to make the entire class generic- add a template parameter to the declaration for the class and define your HashSet and retrieval functions using that template parameter for the types.
I'm a .Net guy at the moment, though, so I couldn't give you the Java syntax, but using C# syntax it would look something like this:
public class DataSet<T>
{
private Set<T> Data;
public DataSet( T obj )
{
Data = new HashSet<T>();
Data.add( obj );
}
public Iterator<T> getDataObjects()
{
return Data.iterator;
}
}
You could fetch an object from the set and verify its type.
Or you could have multiple sets to contain different types.
Or you could have an instance variable of type Class to act as a discriminator as an instance variable.
Or you could create a proxy object for HashSet using the last technique.
You could use a map to the set
HashMap <Class<?>, HashSet<Object>> data;
HashSet temp = data.get(DataObject.class);
if(temp == null)
{
temp = new HashSet();
data.put(DataObject.class, temp);
}
temp.add(obj);
Then you will get the best of both worlds.
Sounds like your design needs to be re-thought.
Also, to be clear on Generics; you cannot access the type at runtime. The type parameter is only for compile-time checking and is completely gone (type erasure) at runtime.
What does this class offer that CachedRowSet does not?
Sorry, I don't consider this to be a very good abstraction. If I were a member of your team, I wouldn't use it.
Your syntax doesn't look correct to me, either. IntelliJ agrees with me: it won't compile.
This does:
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
public class DataSet
{
private Set<DataObject> data;
public DataSet(DataObject obj)
{
this.data = new HashSet<DataObject>();
data.add(obj);
}
public DataSet(DataObject[] objs)
{
data = new HashSet<DataObject>();
data.addAll(Arrays.asList(objs));
}
// etc.
}
Still a poor abstraction. Rethink it.
You could add an property to your dataset class (an enumerated value, boolean or type) that specifies which type was used to initialize the hashset.
Set the property in the appropriate constructor. This allows you to bypass getting an element out of the collection to check its type.
pseudo-code:
public class DataSet
{
private HashSet Data;
private Type _iw = null;
public Type InitializedWith { return _iw; }
public DataSet(DataObject)
{
...
_iw = typeof(DataObject);
}
public DataSet(ObjectRelationship)
{
...
_iw = typeof(ObjectRelationship)
}
I'm going to follow duffymo's advice and just use better abstraction. I'm going to make multiple classes for each specific type I plan to use (each implementing a common interface) so that I can just bypass this dumb problem.
It'll add a minuscule bit of overhead during the process of creating each DataSet object of correct type, but I suppose that's just how it goes.
I don't know what DataObject gives you over and above an Object.
I think an object-oriented approach to your problem would use classes that reflected your domain of interest (e.g., Invoice, Customer, etc.). The persistence layer would hide the persistence details.
A common way to accomplish this is to use the Data Access Object, which might look like this in Java:
public interface GenericDao<T>
{
T find(Serializable id);
List<T> find();
void save(T obj);
void update(T obj);
void delete(T obj);
}
Now you're dealing with objects instead of things that smack of relational databases. All the CRUD details are hidden behind the DAO interface.

Categories