两个默认方法相互调用

Two default methods calling each other

我有这样的界面:

    public interface Foobar
    {
        default void foo( Bar bar )
        {
            foo( bar, 1 );
        }

        default void foo( Bar bar, int n )
        {
            for ( int i = 0; i < n; i++ )
            {
                foo( bar );
            }
        }
    }

一开始我觉得这样就好了:

    default void foo( byte[] b )
    {
        foo( b, 0, b.length );
    }

    void foo( byte[] b, int off, int len );

我的问题是我想执行 foo 一次或 n 次。 任何实施 class 都可以覆盖其中一个或两个。 (第二种方法用于性能关键系统中的批处理目的)

但我使用 default 的解决方案似乎不是很好的风格,因为可以覆盖它们的 none 并且调用任何一个都会导致无限循环(并最终导致 Whosebug) .

所以,我的问题是:什么是好的 OOP 风格妥协?

您的 IFoo 界面可能如下所示 -

public interface IFoo {

    default void foo(Bar bar, int n) {
        for (int i = 0; i < n; i++) {
            foo(bar);
        }
    }

    void foo(Bar bar);

}

你的 Foo class 实现了 IFoo 接口可以像这样 -

public class Foo implements IFoo{

    @Override
    public void foo(Bar bar) {
        // process foo logic

    }

}

您不需要在界面内强制执行单循环逻辑,而是直接调用 foo。