java接口中只有一个方法_何时在Java中使用单一方法接口

使用

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); }

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值