gpt4 book ai didi

java - 通过构造函数传递对象引用

转载 作者:行者123 更新时间:2023-12-01 16:34:54 25 4
gpt4 key购买 nike

我正在构建一个相对较大的面向对象程序。我有一个名为 AerodynamicCalculator 的类,它执行大量计算并将结果分布在系统中。我主要担心的是,当我向构造函数签名添加更多参数时,它会变得越来越大。

如下所示,我已经有九个对象引用传递到此构造函数中,但我还需要另外七个。我是否正确创建了这个对象?我的理解是,您将关联的对象引用传递给构造函数,并将类的局部变量分配给对象引用。如果是这种情况,使用所有必需的对象正确初始化我的类的唯一方法是将它们传递给构造函数,这会导致签名很长。

public AreodynamicCalculator(AircraftConfiguration config, AileronOne aOne,
AileronTwo aTwo, ElevatorOne eOne, ElevatorTwo eTwo, Rudder r,
Rudder rr, RateGyros rG) {
// ...
}

有关此方法的任何建议都会非常有帮助,提前致谢。

最佳答案

如上所述 - 这可能表明您的类(class)做得太多了,但是,对于这个问题有一个常用的“解决方案”。

构建器模式经常在这种情况下使用,但是当您有许多具有不同参数的构造函数时,它也非常有用,构建器很好,因为它使参数的含义更清晰,特别是在使用 boolean 文字时。

这是构建器模式,其工作方式如下:

AreodynamicCalculator calc = AreodynamicCalculator.builder()
.config(theAircraftConfiguration)
.addAileron(aileronOne)
.addAileron(aileronTwo)
.addElevator(elevatorOne)
.addElevator(elevatorTwo)
.addRudder(rudderOne)
.addRudder(rudderTwo)
.build()

在内部,构建器将存储所有这些字段,当调用 build() 时,它将调用一个采用这些字段的(现在是私有(private)的)构造函数:

class AreodynamicCalculator {
public static class Builder {
AircraftConfiguration config;
Aileron aileronOne;
Aileron aileronTwo;
Elevator elevatorOne;
Elevator elevatorTwo;
...

public Builder config(AircraftConfiguration config) {
this.config = config;
return this;
}

public Builder addAileron(Aileron aileron) {
if (this.aileronOne == null) {
this.aileronOne = aileron;
} else {
this.aileronTwo = aileron;
}
return this;
}

// adders / setters for other fields.

public AreodynamicCalculator build() {
return new AreodynamicCalculator(config, aileronOne, aileronTwo ... );
}
}

// this is the AircraftConfiguration constructor, it's now private because
// the way to create AircraftConfiguration objects is via the builder
//
private AircraftConfiguration config, AileronOne aOne, AileronTwo aTwo, ElevatorOne eOne, ElevatorTwo eTwo, Rudder r, Rudder rr, RateGyros rG) {
/// assign fields
}
}

关于java - 通过构造函数传递对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10231605/

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