我最近在MorseString
课上遇到了这个问题。我有两个不同的构造函数,它们做不同的事情,但采用相同的数据类型:
/*
* Constructor that takes the Morse Code as a String as a parameter
*/
public MorseString(String s) {
if(!isValidMorse(s)) {
throw new IllegalArgumentException("s is not a valid Morse Code");
}
// ...
}
和
/*
* Constructor that takes the String as a parameter and converts it to Morse Code
*/
public MorseString(String s) {
// ...
}
我想出了这个解决方案:
public MorseString(String s, ParameterType type) {
if(type == ParameterType.CODE) {
if(!isValidMorse(s)) {
throw new IllegalArgumentException("s is not a valid Morse Code");
}
// Constructor that takes Morse
} else {
// Constructor that takes String
}
}
但它看起来很丑。还有其他解决方案吗?
是的。摆脱构造函数并使用其他方法,例如
1)工厂方法,所以你会有这样的方法:
class MorseString {
private MorseString(){};
public static MorseString getFromCode(String s) {
// ...
}
public static MorseString getFromString(String s) {
// ...
}
}
// Usage: MorseString.getFromCode(foo);
或
2)一个生成器,所以你会有这样的方法
class MorseString {
private MorseString(){};
static class Builder {
Builder initFromCode(String code) {
// ..
return this;
}
Builder initFromString(String str) {
// ..
return this;
}
MorseString build() {
// ..
}
}
}
// Usage: MorseString.Builder.initFromCode(foo).build();
如果你有一个高度复杂的创建逻辑,大量的参数,在创建过程中只有一些信息的对象,一些初步验证等,那么构建器是很好的。工厂方法是一种较轻的方法,适用于有多种方法创建参数略有不同的对象的情况。
由于其中一个构造函数需要现成的摩尔斯电码数据(所以它更像是一个"构造函数" - 从字面上从数据构造一个对象),而另一个必须进行一些转换,因此创建一个称为convert
的静态工厂方法可能更有意义:
/*
* Constructor that takes the Morse Code as a String as a parameter
*/
public MorseString(String s) {
if(!isValidMorse(s)) {
throw new IllegalArgumentException("s is not a valid Morse Code");
}
// ...
}
/*
* Factory method that takes the String as a parameter and converts it to Morse Code
*/
public static MorseString convert(String s) {
// ...
return new MorseString(convertedString);
}
因此,如果你有一个有效的莫尔斯电码字符串,你可以使用构造函数把它变成一个对象。 但是,如果您有需要转换的数据,则可以调用静态工厂方法:
MorseString ms = MorseString.convert(myString);