【发布时间】:2018-12-12 17:26:35
【问题描述】:
我想迭代一个作用于每个项目的集合。
Collection<Listener> listeners = ....
interface Listener {
void onEventReceived();
void onShutDown();
}
代码可能是:
void notifyShutdown() {
for(Listener listener:listeners){
listener.onShutDown();
}
}
我想抓住 java8 的 lambda,所以我声明了一个辅助接口:
interface WrapHelper<T> {
void performAction(T item);
}
还有一个通知方法
public void notifyListeners(WrapHelper<Listener> listenerAction) {
for (Listener listener : listeners) {
listenerAction.performAction(listener);
}
}
所以我可以声明如下方法:
public void notifyEventReceived() {
notifyListeners(listener -> listener.onEventReceived());
}
public void notifyShutDown() {
notifyListeners(listener -> listener.onShutDown());
}
我的问题是:我是否需要自己声明接口WrapHelper,在Android API
【问题讨论】:
-
我不了解Android API,但是您可以访问JDK8的
java.util.function.Consumer吗?这将对应于您的WrapHelper。 -
有很多选项,例如java-support、LWS、android-retrostreams。仅举几例。
标签: java android java-8 functional-programming