【问题标题】:interface method that does not make sense for all implementing classes对所有实现类都没有意义的接口方法
【发布时间】:2015-12-05 14:37:19
【问题描述】:

所以我在这个使用 Spring 并在各处注入接口的好项目中工作。问题是:在我的一个实现者中,我有这个方法在那个特定的实现中才有意义。我应该如何在其他类中实现这个方法? 例如:

 public interface A {
           public String methodThatMakesSenseOnlyToImplementationA();
       }

现在是实现类:

 public class ImplementingInterfaceA implements A {
            public String methodThatMakesSenseOnlyToImplementationA() {
                 //many many crazy things here
            }
 }

对于这个类,我必须实现方法,但是返回空字符串看起来很脏。

public class Nothing implements A {
        public String methodThatMakesSenseOnlyToImplementationA() {
             // this implementation will never use the method methodThatMakesSenseOnlyToImplementationA
        }
    }

如何以一种好的方式解决这个问题?

【问题讨论】:

  • 分割你的界面,有一个通用的,一个只用于实现A
  • 这个方法是怎么用的?调用者是否知道正在调用该方法的对象属于具有有用实现的类型?
  • 如果Nothing类不需要实现methodThatMakesSenseOnlyToImplementationA()方法,为什么还要实现接口A
  • 嗨@FedericoPeraltaSchaffner。该接口还有其他需要实现的方法。该特定方法表示特定于特定实现的操作。它需要在接口上,因为在 spring 中我们使用接口声明字段,而不是特定的实现。
  • 嗨@MaartenWinkels,请阅读上面的评论。该方法必须通过接口调用,因为该字段是使用 Spring 注入的,因此我们将它们声明为接口类型而不是特定实现

标签: java spring oop design-patterns interface


【解决方案1】:

当没有合理的实现并且你知道该方法没有被调用时,抛出一个UnsupportedOperationException

【讨论】:

  • 我喜欢这个解决方案,因为它简单而且优雅地解决了我的问题。
【解决方案2】:

而不是为类Nothing 实现接口A。扩展类 ImplementingInterfaceA 。它将继承已经实现的方法。

或者如果您使用的是 java 8,请在界面中使用默认方法。

【讨论】:

    【解决方案3】:

    您可以将额外方法移动到另一个 interface- 比如说 B- 这样您将拥有两个接口 AB

    • 方法一

      public interface B {
          //here are the methods that make some sense for all the classes
      }
      

      接口可以扩展接口:

      public interface A extends B {
          public String methodThatMakesSenseOnlyToImplementationA();
      }
      

      这些类可以实现不同的接口:

      public class ImplementingInterfaceA implements A {
          . . .
      }
      
      public class Nothing implements B {
          . . .
      }
      
    • 方法二

      您可以拥有完全分离的接口:

      public interface B {
          //here are the methods that make some sense for all the classes
      }
      
      public interface A {
          public String methodThatMakesSenseOnlyToImplementationA();
      }
      

      类可以实现一个或多个接口:

      public class ImplementingInterfaceA implements A, B {
          . . .
      }
      
      public class Nothing implements B {
          . . .
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多