[英]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
方法中,則需要返回一個實現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 + "\"'";
}
如果練習允許您創建其他類,您可以添加一個新的 class,例如實現接口的QuotedStringCombiner
:
public class QuotedStringCombiner implements StringCombiner {
@Override
public String combine(String first, String second) {
return "'\"" + first + "\" \"" + second + "\"'";
}
}
在CombinerFactory
的getQuotedCombiner
方法上,您可以返回此 class 的新實例:
static StringCombiner getQuotedCombiner() {
return new QuotedStringCombiner();
}
或者,實現 Singleton 模式,以避免在每次請求引用的組合器時創建實例:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.