两个构造函数执行不同的操作但采用相同的数据类型

The*_*Cup 3 java constructor

我最近遇到了这个问题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");
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

/*
 * Constructor that takes the String as a parameter and converts it to Morse Code
 */

public MorseString(String s) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我想出了这个解决方案:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

但它看起来很难看.还有其他方法吗?

eis*_*eis 9

是.摆脱你的构造函数,而使用其他一些方法,如

1)工厂方法,所以你有这样的方法:

class MorseString {
    private MorseString(){};
    public static MorseString getFromCode(String s) {
        // ...
    }
    public static MorseString getFromString(String s) {
        // ...
    }
}

// Usage: MorseString.getFromCode(foo);
Run Code Online (Sandbox Code Playgroud)

要么

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();
Run Code Online (Sandbox Code Playgroud)

如果你有一个高度复杂的创建逻辑,很多参数,在创建过程中只有一些信息的对象,一些初步验证等,那么构建器就是好的.对于你有多种方式的工厂方法,工厂方法更轻松使用稍微变化的参数创建对象.