我正在构建一个相对较大的面向对象的程序。我有一个名为AerodynamicCalculator的类,它执行大量计算并在系统中分发结果。我主要担心的是,当我添加更多参数时,我的构造函数签名会变得越来越大。
如下所示,我已经有9个对象引用被传递到这个构造函数中,但我还需要另外7个。我是否正确地创建了此对象?我的理解是将相关的对象引用传递给构造函数,并将类的局部变量分配给对象引用。如果是这种情况,使用所有必需的对象正确初始化我的类的唯一方法是将它们传递给构造函数,这会导致非常长的签名。
public AreodynamicCalculator(AircraftConfiguration config, AileronOne aOne,
AileronTwo aTwo, ElevatorOne eOne, ElevatorTwo eTwo, Rudder r,
Rudder rr, RateGyros rG) {
// ...
}任何关于这种方法的建议都会非常有帮助,提前谢谢。
发布于 2012-04-19 23:37:41
如前所述-这可能是你的类做了太多的标志,然而,有一个通用的“解决方案”来解决这个问题。
构建器模式通常用于这种情况,但当您有许多具有不同参数的构造器时,它也非常有用,构建器很好,因为它使参数的含义更清晰,特别是在使用布尔型文字时。
以下是构建器模式,其工作方式如下所示:
AreodynamicCalculator calc = AreodynamicCalculator.builder()
.config(theAircraftConfiguration)
.addAileron(aileronOne)
.addAileron(aileronTwo)
.addElevator(elevatorOne)
.addElevator(elevatorTwo)
.addRudder(rudderOne)
.addRudder(rudderTwo)
.build()在内部,构建器将存储所有这些字段,当调用build()时,它将调用一个(现在是私有的)构造函数,该构造函数接受这些字段:
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
}
}发布于 2012-04-19 23:39:22
类似于使用daveb的响应中建议的构建器模式,您可以使用Spring等依赖注入框架。
https://stackoverflow.com/questions/10231605
复制相似问题