如何减少构造函数重载的代码

mil*_*ind 1 java constructor overloading

在我的一个课程中,我有很多这样的构造函数.

public MyData(int position,String songName,String duration, boolean e) {

    //initialization of above variable like int, string,string and boolean

}

public MyData(String songName, String artistName, String duration,String downloadPath, String songSize, String albumName,String url,String trackId, boolean e) 
{
 //initialization of above variable like String,String,String,String,String,String,String,String and boolean

}
Run Code Online (Sandbox Code Playgroud)

还有一些像上面那样.现在是调用时间,我只调用那个我需要数据的构造函数.但我不认为我的流程是好的,所以我需要一些帮助来减少我的代码以及创建良好的流程.如果有人有良好的流程来实现这一目标,那么请分享.

提前致谢.

Jon*_*eet 5

假设您正在有效地应用默认值,通常最好的方法是使用一个"完整"构造函数并让其他人调用它.例如:

public Foo(String name)
{
    // Default the description to null
    this(name, null);
}

public Foo(String name, String description)
{
    this.name = name;
    this.description = description;
}
Run Code Online (Sandbox Code Playgroud)

在重载构造函数方面,你仍然会遇到很多错误,但至少每个"额外"构造函数都不包含实际代码 - 只需调用另一个构造函数.如果可能,将构造函数链接在一起,以便任何特定值的默认值仅在一个位置指定 - 或使用常量.这样你就可以保持一致性.

另一种选择是在构建器模式之后使用"参数对象" - 创建另一个类,其唯一目的是保存构造函数参数的数据.这应该是可变的,使用所有不同值的setter.通常,让setter返回构建器是有用的,因此您可以使用:

FooParameters parameters = new FooParameters()
    .setName("some name")
    .setDescription("some description");

// Either a constructor call at the end, or give FooParameters
// a build() or create() method
Foo foo = new Foo(parameters);
Run Code Online (Sandbox Code Playgroud)

如果您构建的主类型是不可变类型,这将特别有用 - 这意味着您可以在调用代码中应用条件逻辑来设置一些参数而不是其他参数.Java框架本身使用这种方法ProcessBuilder,虽然我个人并不热衷于重载方法名称以返回值或根据您是否提供参数设置值的方式:(

请注意,在最后的片段构造函数调用上面的注释-如果你的助手类只用于创建一个单一类型的对象永远有用,你可以给它一个额外的方法(build,create,start,无论是最合适的)采取的地方构造函数调用.这允许您以流畅的方式构建整个最终对象.

构建器模式的Java实现中的一个选项是使用嵌套类型,例如

Foo foo = new Foo.Builder().setName(...).setDescription(...).build();
Run Code Online (Sandbox Code Playgroud)

这避免了用另一个类来污染你的包,这个类对构建实例有用Foo.