如何用点连接方法? - 重构

How do I connect methods with dots? - Refactoring

我正在尝试重构我的代码。但我不知道如何做我想做的事。我不知道它是怎么叫的,所以我没有用 google 找到它。 我的代码:

public void print(int from, int to) {
        // TODO Auto-generated method stub
        
        for(;from<=to;from++)
        {
            if(from % 3 == 0)
            {
                if(from % 5 == 0)
                {
                    System.out.println("Fizz Buzz");
                }
                else 
                {
                    System.out.println("Fizz");
                }
            }
            else
            {
                if(from % 5 == 0)
                {
                    System.out.println("Buzz");
                }
                else 
                {
                    System.out.println(from);
                }
            }
        }
        
    }

我想重构所有内容,所以最终版本如下所示:

print("Fizz").If(from).IsMultipleOf(3);
print("Buzz").If(from).IsMultipleOf(5);
print("Fizz Buzz").If(from).IsMultipleOf(3).And.IsMultipleOf(5);

或者像这样:

if(If(from).IsMultipleOf(3) && If(from).IsMultipleOf(5))
{
print("Fizz Buzz");
}

因此“If(from).IsMultipleOf(3)”应 return true/false 如果为真,则应执行 print() 函数。但是我不知道如何用点(“.”)来做。

有人可以告诉我 google 的正确术语或给我举个例子吗?

-提前致谢!

您需要寻找 Fluent Api PatternBuilder Pattern

简单示例

public class CheckTest {

    private int num;

    // private constructor for avoiding new CheckTest()
    private CheckTest(int num){ 
        this.num = num;
    } 

    // must start with Print.num(...); on static method
    // see we are returning the same class to use other methods in one line
    public static CheckTest num(int num){ 
        return new CheckTest(num);
    }

    // can be called by Print.num().isMultipleOf()
    public boolean isMultipleOf(int muiltipleOf){ 
        return ( this.num % muiltipleOf ) == 0;
    }

    // can be called by Print.num().isMultipleOfThenPrint()
    public void ifIsMultipleOfThenPrint(int muiltipleOf, String msgToPrint){
        if( isMultipleOf(muiltipleOf))
            System.out.println(msgToPrint);
    }
}

使用我们简单的 class


if( CheckTest.num(10).isMultipleOf(5) && CheckTest.num(15).isMultipleOf(5) ){
    System.out.println("print");
}

CheckTest.num(15).ifIsMultipleOfThenPrint(5,"print");