【问题标题】:What is the use case scenario for interface type method which return type is same name where its belongs to?返回类型与其所属的名称相同的接口类型方法的用例场景是什么?
【发布时间】:2018-05-04 18:35:18
【问题描述】:

我在查看代码片段时在某个地方看到过,但我没有机会询问用例,我无法弄清楚这个接口将如何实现。当您覆盖方法时 A() 那么你应该返回一些实现Feature的东西。下面的例子,

 public interface Feature
 {  
        public Feature A(); 
 }

任何建议都会很棒。提前谢谢..

【问题讨论】:

  • Builder 模式实现很常见。无法给出代码示例(我在手机上),但我相信你会在网上找到它。
  • 各种各样的东西;工厂、建造者、任何你需要访问接口实现的地方。

标签: java design-patterns methods interface


【解决方案1】:

你可以这样做

public class MyClass implements Feature {

  public Feature A() {
    //do stuff
    return this; //since MyClass implements Feature we could return this
  }
}

正如@daniu 提到的,这可以用于方法链接。您可以检查StringBuilder 的代码。因为append(String s) 返回StringBuilder 的实例,你可以这样做

StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("world");

如果apeend()返回void而不是下面的代码

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("world");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多