1

可以Agents在 AnyLogic 中标记为abstract吗?如果是这样,怎么做?我正在尝试从 继承某些方法,但不是其他方法,因为父级实现它们Agent是没有意义的。Agent

4

1 回答 1

2

您不能在GUI 设计的 Agentabstract中声明任何内容(类或方法(AnyLogic 函数)),但您可以将 Agent 创建为用户定义的 Java 类(即,通过 New --> Java Class),即. 为此,您需要知道适当的构造函数签名,AnyLogic 没有记录(但您可以通过查看为任何代理生成的 Java 代码很容易地看到它们)。因此,您将需要如下所示的内容(注意似乎从未使用过的默认构造函数):abstract

public abstract class MyAbstractAgent extends Agent
                                implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * Constructor in form required for an Agent subclass to be instantiated and for
     * superclass instantiation (as gleaned from looking at Java source of
     * visually-created Agents)
     */
    public MyAbstractAgent(Engine engine,
                           Agent owner,
                           AgentList<? extends MyAbstractAgent> collection) {

        super (engine, owner, collection);

    }

    /*
     * Simple constructor as now included in all AnyLogic 7 generated Agent code. Don't
     * understand when this would be invoked cf. the others so let's assert that we 
     * don't think it should
     */
    public MyAbstractAgent() {

        throw new AssertionError("Not expecting simple constructor to be used!");

    }

    // Using package visibility (the default for GUI-designed functions)
    abstract specialAbstractFunction();

}

但是,由于您可能想要混合非抽象方法,因此最好将这些方法放在 GUI 设计的代理中(所以上面的类extends MyGUI_Agent或类似的类),但这意味着有一个只有抽象方法的抽象代理(和因此是一种“不必要的”继承级别)。

另一种方法是通过强制运行时符合任何子类代理中所需的(覆盖)方法来“近似”抽象类。只需在父级中定义您的 required-in-subclass-Agent 函数,如下所示:

throw new IllegalStateException("Subclass must implement specialAbstractMethod()");

(或者,更好的是,扔你自己的MissingRequiredOverrideException或类似的)。不是一个纯粹主义者,但也不是另一种方法。

于 2014-11-25T00:28:15.940 回答