2014-12-24 22 views
3

我最近遇到了這個問題,我的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 
    } 
} 

但它看起來醜陋。其他解決方案?

+0

使用函數代替構造函數。 –

+3

它確實很醜,但有2個方法/構造函數具有相同的簽名是不可能的。 – Gumbo

+1

這個問題似乎是無關緊要的,因爲它涉及代碼審查。它會更適合[codereview](codereview.stackexchange.com)。 –

回答

4

由於其中一個構造函數期待現成的莫爾斯碼數據(因此它更像是一個「構造函數」 - 從字面上用數據構造一個對象),另一個必須做一些轉換,它可能使更多感,使東西叫做靜態工廠方法一樣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); 
9

是的。擺脫你的構造和使用,而不是其他一些方法,如

1)Factory Method,所以你有這樣的方法:

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(); 

方法的建設者是好的,如果你有一個非常複雜的創建邏輯,大量的參數,具有ONL對象y他們在創作中的一些信息,一些初步的驗證等等。工廠方法是一種更輕的方法,在這種情況下,您可以通過多種方式創建具有輕微變化參數的對象。

+0

這可能是一個更好的解決方案,可以避免您傳入的字符串類型不明確。 – mellamokb

相關問題