Java如何实现这个接口?

Java how to implement this interface?

我正在做一些不包含答案的测试题,我已经被困了一段时间。 我有这个界面(Stringcombiner.java)

package section3_apis.part1_interfaces;

public interface StringCombiner {
    String combine(String first, String second);
}

和这家工厂 (CombinerFactory.java)

package section3_apis.part1_interfaces;

public class CombinerFactory{
    /**
     * This method serves a StringCombiner that will surround the given arguments with double quotes,
     * separated by spaces and the result surrounded by single quotes.
     *
     * For example, the call
     *      combiner.combine("one", "two")
     * will return '"one" "two"'
     * @return quotedCombiner
     */
    static StringCombiner getQuotedCombiner() {
        //YOUR CODE HERE (and remove the throw statement)

        throw new UnsupportedOperationException("Not implemented yet");
    }

我也折腾了好久,还是解决不了。 到目前为止我已经尝试过: 我试图让 CombinerFactory 实现接口,然后添加覆盖,但我不明白我如何在 getQuotedCombiner 中使用字符串组合。我还尝试在 getQuotedCombiner 中创建一个新的 Stringcombiner 实例,但我很确定这不是我应该做的。当我尝试其中一种方法时,它要求我输入要组合的值,但最终目标是使用 Junit 测试。我假设我需要放置某种占位符或实现该方法的主要 class 但仍然使该方法保持打开状态以供从外部使用(通过测试)我在这里有点吐口水,只是尝试把我认为我应该做什么的想法写在纸上。

如果能在正确的方向上提供有关如何解决此问题的指导,我将不胜感激。

假设您只能将代码放入 getQuotedCombiner 方法中,您需要 return 一个实现 StringCombiner 接口的匿名 class。 例如:

static StringCombiner getQuotedCombiner() {
    return new StringCombiner() {
        public String combine(String first, String second) {
            return "'\"" + first + "\" \"" + second + "\"'";
        }
    };
}

对于 Java 8,您可以使用 lambda 表达式简化它:

static StringCombiner getQuotedCombiner() {
    return (first, second) -> "'\"" + first + "\" \"" + second + "\"'";
}

如果练习允许您创建其他 classes,您可以添加一个新的 class,例如实现接口的 QuotedStringCombiner

public class QuotedStringCombiner implements StringCombiner {
    
    @Override
    public String combine(String first, String second) {
        return "'\"" + first + "\" \"" + second + "\"'";
    }
}

并且在 CombinerFactorygetQuotedCombiner 方法上,您可以 return 这个 class:

的新实例
static StringCombiner getQuotedCombiner() {
    return new QuotedStringCombiner();
}

或者,实现单例模式,以避免每次请求引用组合器时都创建一个实例:

private static final QuotedStringCombiner QUOTED_COMBINER_INSTANCE = new QuotedStringCombiner();

static StringCombiner getQuotedCombiner() {
    return QUOTED_COMBINER_INSTANCE;
}
public class StringCombinerImpl implements StringCombiner {
    public String combine(String first, String second) {
        throw new UnsupportedOperationException("Not implemented yet");
    }
}

只需将 throw 语句更改为实现该方法预期功能所需的代码即可。

要使用它,请将实例创建添加到 getQuotedCombiner:

static StringCombiner getQuotedCombiner() {
    return new StringCombinerImpl();
}