【问题标题】:Java how to implement this interface?Java如何实现这个接口?
【发布时间】:2021-01-08 11:15:15
【问题描述】:

我正在处理一些不包含答案的考试题,我已经被困了一段时间。 我有这个接口(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 测试。我假设我需要放置某种占位符或实现该方法的主类,但仍然使该方法保持开放以供外部使用(通过测试)我在这里有点吐槽,只是想了解一下我的想法在纸上写下我认为我应该做什么。

对于如何解决这个问题,我希望得到一些正确方向的指导。

【问题讨论】:

标签: java interface


【解决方案1】:

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

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 + "\"'";
}

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

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

CombinerFactorygetQuotedCombiner 方法上,您可以返回此类的新实例:

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

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

private static final QuotedStringCombiner QUOTED_COMBINER_INSTANCE = new QuotedStringCombiner();

static StringCombiner getQuotedCombiner() {
    return QUOTED_COMBINER_INSTANCE;
}

【讨论】:

    【解决方案2】:
    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-12
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2019-03-29
      • 2015-03-30
      • 2014-03-04
      • 1970-01-01
      相关资源
      最近更新 更多