gpt4 book ai didi

java - 如何在调用任何函数之前在 Fluent API 中传递参数?

转载 作者:行者123 更新时间:2023-11-30 07:47:23 24 4
gpt4 key购买 nike

我有这样的类(class)

public class AImpl implements A {
private String variable = "init";

@Override
public A choice(A... choices) {
return this;
}

@Override
public A execute() {
variable = "execute";
return this;
}
}

我可以像这样使用它(简单的例子)

new AImpl().choice(
new AImpl[] {
new AImpl().execute(),
new AImpl()
};
)

或者像这样(更复杂的例子,具有可变的期望值)

new AImpl().choice(                       //variable == "init"
new AImpl[] {
new AImpl().execute(), //variable == "init". Set to "execute"
new AImpl().choice( //variable == "init"
new AImpl[] {
new AImpl() //variable == "init"
}
),
new AImpl().execute().choice( //variable == "init". Set to "execute"
new AImpl[] {
new AImpl(), //variable == "execute"
new AImpl() //variable == "execute"
}
),
};
)

我想要实现的目标

每次有选择时,我都想将变量的最后一个值传播到每个新实例。这是复杂示例的图形版本,其中我圈出了所谓的“传播”

enter image description here

我的问题是什么

在调用任何其他函数之前(在调用 execute 之前),如何将此变量传播到 choices 列表中的所有对象 在上面的简单示例中,因为这个函数使用(并且可以修改)这个变量)。

我尝试过的

  • 我无法使用构造函数来执行此操作,因为我没有对变量的引用

    public AImpl(String variable) {
    this.variable = variable;
    }
  • 此代码将不起作用,因为变量将在所有函数之后设置

    @Override
    public A choice(A... choices) {
    for(A a : choices) {
    a.setVariable(variable);
    }
    }
  • 我尝试使用Builder(例如设置所有值并仅在最后创建实例,例如从选择函数)。但链接函数 executechoice 是有意义的 (...execute().execute().choice()... )。因此,构建器变得难以创建并且可能变得非常大。

  • 我还尝试将变量移动到 context 类,但如果在 choices 中我有另一个选择(更多的情况),则它不起作用复杂的例子)。这是我当前的上下文类

    public class Context {
    private static Context instance = null;
    private String variable;

    private Context(){};

    public String getVariable() {
    return variable;
    }

    public void setVariable(String variable) {
    this.variable = variable;
    }

    public static void set(String variable) {
    if(Context.instance == null)
    Context.instance = new Context();
    Context.instance.setVariable(variable);
    }

    public static String get() {
    if(Context.instance == null)
    throw new NullPointerException();
    return Context.instance.getVariable();
    }
    }

最佳答案

问题是新的 AImpl 实例需要继承其“父”AImpl 实例的上下文,即调用 choice() 的实例。您无法使用 new 运算符来做到这一点。您应该使用一个方法来创建带有继承变量的实例。

public A[] createChoices(int count, A optionalDefaultValues...) {
// return an array of clones of itself (possibly with adjusted defaults)
}

关于java - 如何在调用任何函数之前在 Fluent API 中传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com