How to get java singleton object manager to return any type of object?

Posted by Robert on Stack Overflow See other posts from Stack Overflow or by Robert
Published on 2010-05-16T18:42:12Z Indexed on 2010/05/16 18:50 UTC
Read the original article Hit count: 126

I'm writing an interactive fiction game in java from scratch. I'm currently storing all of my game object references in a hashmap in a singleton called ObjectManager. ObjectManager has a function called get which takes an integer ID and returns the appropriate reference. The problem is that it returns a BaseObject when I need to return subclasses of BaseObject with more functionality.

So, what I've done so far is I've added a getEntity function which returns BaseEntity (which is a subclass of BaseObject). However, when I need the function to return to an object that is a subclass of BaseEntity that has added, required functionality, I will need to make another function. I know there is a better way, but I don't know what it is. I know very little of design patterns, and I'm not sure which one to use here. I tried passing 'class' as a parameter, but that didn't get me anywhere.

public BaseObject get(int ID){
    return (BaseObject)refMap.get(ID);
}

public BaseEntity getEntity(int ID){
    return (BaseEntity)refMap.get(ID);
}

Thanks, java ninjas!

© Stack Overflow or respective owner

Related posts about java

Related posts about classes