使用
Java 8,保持单一方法接口是非常有用的,因为单个方法接口将允许使用闭包和“函数指针”.因此,每当您的代码针对单个方法接口编写时,客户端代码可能会传递闭包或方法(必须具有与单个方法接口中声明的方法兼容的签名),而不必创建匿名类.相反,如果您使用多个方法制作一个界面,那么客户端代码就不会有这种可能.它必须始终使用实现接口的所有方法的类.
所以作为一个常见的指导方针,可以说:如果只向客户端代码公开单一方法的类可能对某些客户端有用,那么为该方法使用单个方法接口是一个好主意.一个反例子就是迭代器接口:在这里,只有一个没有一个hasNext()方法的next()方法是没有用的.由于拥有只实现其中一种方法的类是没有用的,因此在此处拆分此接口不是一个好主意.
例:
interface SingleMethod{ //The single method interface
void foo(int i);
}
class X implements SingleMethod { //A class implementing it (and probably other ones)
void foo(int i){...}
}
class Y { //An unrelated class that has methods with matching signature
void bar(int i){...}
static void bar2(int i){...}
}
class Framework{ // A framework that uses the interface
//Takes a single method object and does something with it
//(probably invoking the method)
void consume(SingleMethod m){...}
}
class Client{ //Client code that uses the framework
Framework f = ...;
X x = new X();
Y y = new Y();
f.consume(x); //Fine, also in Java 7
//Java 8
//ALL these calls are only possible since SingleMethod has only ONE method!
f.consume(y::bar); //Simply hand in a method. Object y is bound implicitly
f.consume(Y::bar2); //Static methods are fine, too
f.consume(i -> { System.out.println(i); }) //lambda expression. Super concise.
//This is the only way if the interface has MORE THAN ONE method:
//Calling Y.bar2 Without that closure stuff (super verbose)
f.consume(new SingleMethod(){
@Override void foo(int i){ Y.bar2(i); }
});
}