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

Mik*_*ard 0 java object

我正在构建一个相对较大的面向对象程序.我有一个叫做的类AerodynamicCalculator,它执行大量计算并在系统周围分配结果.我主要担心的是,当我向其添加mor参数时,我的构造函数签名变得越来越大.

如下所示,我已经将9个对象引用传递给了这个构造函数,但我需要另外7个.我正确创建了这个对象吗?我的理解是你将关联的对象引用传递给构造函数,并将class'es局部变量赋给对象引用.如果是这种情况,使用所有必需对象正确初始化我的类的唯一方法是将它们传递给构造函数,这将导致非常长的签名.

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

对此方法的任何建议都会非常有帮助,在此先感谢.

dav*_*veb 6

如上所述 - 这可能是您的课程做得太多的一个标志,但是,这个问题有一个常用的"解决方案".

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

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

AreodynamicCalculator calc = AreodynamicCalculator.builder()
    .config(theAircraftConfiguration)
    .addAileron(aileronOne)
    .addAileron(aileronTwo)
    .addElevator(elevatorOne)
    .addElevator(elevatorTwo)
    .addRudder(rudderOne)
    .addRudder(rudderTwo)
    .build()
Run Code Online (Sandbox Code Playgroud)

在内部,构建器将存储所有这些字段,并且在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
    }
}
Run Code Online (Sandbox Code Playgroud)