簡體   English   中英

Java:所有派生類必須實現的抽象或通用列表

[英]Java: abstract or generic list that all derived classes must implement

我正在用Java為游戲引擎制作基於組件的系統。

我有不同的系統類來處理不同的事情,例如PhysicsSystem,RenderSystem,EditorSystem等。 所有類都繼承自BaseSystem,后者又實現了一個接口ISystem。

我希望所有系統類都具有一個ArrayList,但是每個類中的類型可能有所不同,這意味着RenderSystem可能具有RenderComponents列表,而PhysicsSystem卻具有PhysicsBodyComponents列表。

是否可以在所有派生類隨后實現的BaseSystem類或ISystem接口中定義通用列表或抽象列表? 我對泛型沒有什么經驗,所以對此感到有些困惑。

這是我當前的代碼。 如您所見,我為派生類創建了第二個列表,這很浪費。

interface ISystem
{
    boolean AddToSystem(Component c);
}

abstract class BaseSystem implements ISystem
{
    // can I make this list generic, so it can store any type in derived classes?
    // e.g., Component, IRenderable, IPhysics, etc.
    protected List<Component> _componentList;
}

class RenderSystem extends BaseSystem
{

    //  need to make a second list that stores the specific render components
    List<IRenderable> _renderList = new ArrayList<IRenderable>();

    void Update()
    {
        for (IRenderable r : _renderList)
            r.Render(); // this code is specific to the IRenderable components
    }

    @Override
    public boolean AddToSystem(Component c)
    {
        boolean succesfullyAdded = false;

        if (c instanceof IRenderable)
        {
            succesfullyAdded = true;
            _renderList.add((IRenderable) c);

        } else
            throw new RuntimeException("ERROR - " + c.Name() + " doesn't implement IRenderable interface!");

        return succesfullyAdded;

    }
}

當然,假設您所有的組件都實現了IComponent使用如下所示的代碼:

interface ISystem<ComponentType extends IComponent> {
   public boolean AddToSystem(ComponentType c);
}

如果您不希望具有硬類型依賴關系,則可以刪除extends IComponent ,但這會使處理系統列表更加困難。

我想你需要這樣的東西

private static abstract class AbstractClass<T> {

    final List<T> objects = new ArrayList<T>();
}

private static class ComponentHolder extends AbstractClass<Component> {

    public void add(final Component c) {
        objects.add(c);
    }

    public Component getComponent(final int index) {
        return objects.get(index);
    }
}

在您的示例中,將是這樣的:

abstract class BaseSystem<T> implements ISystem
{
    protected List<T> _componentList = new ArrayList<T>();
}

class RenderSystem extends BaseSystem<IRenderable>
{
    void Update()
    {
        for (IRenderable r : _componentList)
            r.Render(); // this code is specific to the IRenderable components
    }

    @Override
    public boolean AddToSystem(Component c)
    {
        boolean succesfullyAdded = false;

        if (c instanceof IRenderable)
        {
            succesfullyAdded = true;
            _componentList.add((IRenderable) c);

        } else
            throw new RuntimeException("ERROR - " + c.Name() + " doesn't implement IRenderable interface!");

        return succesfullyAdded;

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM