我想把一个转换anonymous class成一个lambda expression.但这个匿名类我使用this关键字.
例如,我写了这个简单的Observer/Observable模式:
import java.util.ArrayList;
import java.util.Collection;
public static class Observable {
private final Collection<Observer> notifiables = new ArrayList<>();
public Observable() { }
public void addObserver(Observer notifiable) { notifiables.add(notifiable); }
public void removeObserver(Observer notifiable) { notifiables.add(notifiable); }
public void change() {
notifiables.forEach(notifiable -> notifiable.changed(this));
}
}
public interface Observer {
void changed(Observable notifier);
}
Run Code Online (Sandbox Code Playgroud)
这个带有匿名类的示例代码(使用this关键字):
public class Main {
public static void main(String[] args) {
Observable observable = new Observable();
observable.addObserver(new …Run Code Online (Sandbox Code Playgroud)