簡體   English   中英

兩個構造函數執行不同的操作但采用相同的數據類型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM