开发者

Using Linked list rendering/Processing loop for multiple object types

So, Iv just recently switched over from c++ to java for android programing, and this may be a simple fix but I haven't been able to figure it out yet :( (and yes iv tried searching, although not 100% sure on the correct lingo, so may have missed it)

Pretty much, Iv got a

public static LinkedList<Object> LList = new LinkedList<Object>();

Defined that is used for rendering and animating object开发者_StackOverflows. The problem is because I have just 1 linked list, and multiple object types I need to use if(LList.get(i) instanceof ship) for each object type.

For example

int i;   
    if(LList.size()>=1)
    {
        for(i=0;i<LList.size();i++)
        {
            if(LList.get(i) instanceof ship)
                ((ship) LList.get(i)).animate(elapsedTime);
            else if(LList.get(i) instanceof Laser)
                ((Laser) LList.get(i)).animate(elapsedTime);
        } 
    }

Call me crazy, but this does not seem like it is the best way. It works...but in c++ all you would simply have to do is make both ship and laser have the same parent then you could call .animate without worrying about the (ship/laser) typecast.

Is there a way to do this in java? I tried the same way as you would in c++ but that didn't seem to work. keep in mind im new to java, so may have simply done it wrong.

I was although thinking that I could modify the LList.add function so you also pre-define the objects type as you add it, that would get rid of the instanceof problem, but not really add any flexibility.

Anyway, Thanks for your time!


There are a couple of ways to do this. The easiest is to define either a base class or an interface that defines the common functionality of all objects in your list. For instance, you might have:

public interface Animatable {
    public void animate(long elapsedTime);
}

public class Ship implements Animatable {
    public void animate(long elapsedTime) {
        // implementation for Ship
    }
}

// etc for other classes

Then you could write:

public static LinkedList<Animatable> LList = new LinkedList<Animatable>();

// ...

for (Animatable object : LList) {
    object.animate(elapsedTime);
}

The same basic pattern would apply if you wanted to use a common base class, with the difference that if there was behavior that had a common implementation in all classes, it could be factored out into the base class.

Another approach is to use the Visitor pattern. Although that is a bit harder to understand at first, it provides for much more flexibility and extensibility over the approach outlined above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜