[英]Passing flags (or not) to a constructor in Java
Having methods with different names for roughly the same task makes sense, for example 例如,使用名称不同的方法来执行大致相同的任务是有意义的
open(String filename);
createThenOpen(String filename); // First create the file with default contents, then process the file.
This naming approach does not work for constructors. 这种命名方法不适用于构造函数。 Imagine the constructor takes a filename as above.
想象一下,构造函数采用如上所述的文件名。 I have various options to handle the two cases:
我有多种选择来处理两种情况:
MyClass(String filename, boolean createNew)
. MyClass(String filename, boolean createNew)
。 Not very nice because a call like MyClass("hello.txt", true)
is cryptic. MyClass("hello.txt", true)
这样的调用是神秘的。 RandomAccessFile(File file, String mode)
where mode
is "r"
, "rw"
and so on. RandomAccessFile(File file, String mode)
中那样,添加一个字符串标志RandomAccessFile(File file, String mode)
其中mode
为"r"
, "rw"
等。 This feels very clunky for my purposes. enum
-flag similar to Files
's copy(Path source, Path target, CopyOption... options)
. Files
的copy(Path source, Path target, CopyOption... options)
的enum
标记copy(Path source, Path target, CopyOption... options)
。 Feels pretty clunky too. Currently I seem to actually favour number (6) above and simply have two methods with different names to be called immediately after a no-parameter constructor. 目前,我似乎实际上更喜欢上面的数字(6),只是有两个名称不同的方法要在无参数构造函数之后立即调用。 Have I overlooked any options, or is there a "given" approach for these scenarios?
我是否忽略了任何选择,或者对于这些情况是否有“给定的”方法?
Edit: as pointed out by others below there is a 7th, perhaps most obvious option, of course: 编辑:正如下面其他人所指出的,当然有第七种,也许是最明显的选择:
使您的构造函数的参数列表protected
,并引入大量名为createFooWithBar()
的public static
方法,并带有调用构造函数的精确参数列表。
Make your constructor private and add public factory methods. 将构造函数设为私有并添加公共工厂方法。 This is a very common pattern, I think.
我认为这是一种非常常见的模式。
Another pattern is the "builder". 另一个模式是“构建器”。 Make the constructor accessible only to classes of the same package.
使构造函数仅可用于同一包的类。 Add in the same package a builder (or more than one builder if you prefer) that will call the constructor and call any other method necessary to construct your object.
在同一程序包中添加一个构建器(如果需要,可以添加多个构建器),该构建器将调用该构造器并调用构造该对象所需的任何其他方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.