如果你能放纵一下我的比喻……
您可能以前见过其中之一:
请注意,我们称它为烤面包机。我们确实不称它为“BreadUtil”。
同样,实用方法可以而且应该放在一个为特定功能命名的类中,而不是“与面包相关的杂项”。
大多数时候,你的静态方法属于一个相关的类;例如,Integer.parseInt 是 Integer 类的静态方法,而不是理论上的 IntegerUtil 或 NumberUtil 类的成员。
过去,创建单独的实用程序类的一种情况是当感兴趣的主要类是接口时。这方面的一个例子是java.util.Collections。但是,从 Java 8 开始,这不是借口,因为接口可以具有静态方法和默认方法。其实 Collections.sort(List) 已经迁移到List.sort了。
如果您有很多实用程序方法,并且您觉得它们会使相关类变得混乱,那么将它们放在单独的类中是可以的,但不要放在“BreadUtil”类中。将“util”一词放在类名(或“utils”、“utilities”、“misc”、“miscellaneous”、“general”、“shared”、“common”或“framework”)中是不可接受的.给类一个有意义的名称,描述这些方法的用途。如果方法过于多样化而不允许使用这样的类名,您可能需要将它们分成多个类。 (只有几个方法的小类是完全可以接受的;很多人甚至认为这是好的设计。)
回到 Integer 示例,如果您觉得这些方法使类变得杂乱无章,您可以像这样创建新类:
public class IntegerMath {
private IntegerMath() { }
public static int compare(int x, int y) { /* ... */ }
public static int compareUnsigned(int x, int y) { /* ... */ }
public static int divideUnsigned(int dividend, int divisor) { /* ... */ }
public static int min(int a, int b) { /* ... */ }
public static int max(int a, int b) { /* ... */ }
public static int remainderUnsigned(int dividend, int divisor) { /* ... */ }
public static int signum(int i) { /* ... */ }
public static int sum(int a, int b) { /* ... */ }
public static long toUnsignedLong(int i) { /* ... */ }
}
public class IntegerBits {
private IntegerBits() { }
public static int bitCount(int i) { /* ... */ }
public static int highestOneBit(int i) { /* ... */ }
public static int lowestOneBit(int i) { /* ... */ }
public static int numberOfLeadingZeros(int i) { /* ... */ }
public static int numberOfTrailingZeros(int i) { /* ... */ }
public static int reverse(int i) { /* ... */ }
public static int reverseBytes(int i) { /* ... */ }
public static int rotateLeft(int i, int distance) { /* ... */ }
public static int rotateRight(int i, int distance) { /* ... */ }
}
public class IntegerParser {
private IntegerParser() { }
public static int parseInt(String s) { /* ... */ }
public static int parseInt(String s, int radix) { /* ... */ }
public static int parseUnsignedInt(String s) { /* ... */ }
public static int parseUnsignedInt(String s, int radix) { /* ... */ }
}
最后一个例子表明没有静态方法可能会更好:
public class IntegerParser {
public IntegerParser() { this(10); }
public IntegerParser(int radix) { /* ... */ }
public int parseInt(String s) { /* ... */ }
public int parseUnsignedInt(String s) { /* ... */ }
}