[英]Two constructors that do different things but take the same data type
我最近遇到了我的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)一个Builder ,所以你有这样的方法
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.