2017-08-15 42 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

谢谢大家的最有帮助的输入。 –