2017-08-15 47 views
-4

我正在嘗試編寫一個Java類來執行基本的字符串操作函數。用於鏈接字符串方法的Java流暢接口

我想這個類可以被調用以某種方式,如:

String tmp = StringUtils.RemoveSpaces(str).RemoveSlashes(); 

String tmp = StringUtils.RemoveSlashes(str).RemoveSpaces(); 

我竭力要弄清楚如何構建這個類。我猜想類中的某些方法或變量將是靜態的,並且方法將返回'this'。那麼如果我們的RemoveSlashes方法返回這個字符串,它將如何返回一個字符串'tmp'?我是否會被迫使用RemoveSlashes.toString()或RemoveSlashes.getString()或類似的效果。似乎有點複雜...

我很感激,如果你能幫助我的方法定義和返回類型。

+2

考慮Builder模式https://en.wikipedia.org/wiki/Builder_pattern#Java –

+1

相關:https://stackoverflow.com/questions/31754786/how-to-implement-the-builder-pattern -in-java-8 – Tom

+0

這樣做會迫使你實現所有方法兩次:onnce作爲一個靜態方法,將一個String作爲參數並返回一個包含臨時結果的對象,並且一次作爲此對象的一個​​實例方法。這是可行的,但是使用StringUtils.fromString(str).removeSlashes()。removeSpaces()。toString()會更簡單。請注意Java命名約定的尊重,BTW。無論如何,你需要一個最終的方法從包裝它的對象中取出字符串。 –

回答

0

這可能會幫助您開始。

public class StringUtil { 

    public static void main(String args[]) { 
     String url = "http://something.com/ \\ponies"; 
     String newValue = StringUtil.str(url).removeSlashes().removeSpaces().uppercase().getValue(); 
     System.out.println(newValue); 
    } 

    private String value; 

    public StringUtil(String value) { 
     this.value = value; 
    } 

    public static StringUtil str(String value) { 
     return new StringUtil(value); 
    } 

    public StringUtil removeSlashes() { 
     value = value.replace("\\", ""); 
     return this; 
    } 

    public StringUtil removeSpaces() { 
     value = value.replace(" ", ""); 
     return this; 
    } 

    public StringUtil uppercase() { 
     value = value.toUpperCase(); 
     return this; 
    } 

    public String getValue() { 
     return value; 
    } 
} 
+0

謝謝大家的最有幫助的輸入。 –