监听
A类监听B类
public class A implements BListener {
public static void main(String[] args) {
B b = new B();
b.addListener(new A());
b.doSomething();
}
@Override
public void handleBEvent() {
System.out.println("B event handled by A");
}
}
interface BListener {
void handleBEvent();
}
class B {
private List<BListener> listeners = new ArrayList<>();
public void addListener(BListener listener) {
listeners.add(listener);
}
public void removeListener(BListener listener) {
listeners.remove(listener);
}
private void notifyListeners() {
for (BListener listener : listeners) {
listener.handleBEvent();
}
}
public void doSomething() {
// do some work
notifyListeners();
}
}
回调
java的回调
public class CallbackExample {
public static void main(String[] args) {
Worker worker = new Worker();
Callback callback = new Callback() {
@Override
public void onComplete() {
System.out.println("Task completed successfully");
}
@Override
public void onError(Exception e) {
System.out.println("Task failed with error: " + e.getMessage());
}
};
worker.doWork(callback);
}
}
interface Callback {
void onComplete();
void onError(Exception e);
}
class Worker {
public void doWork(Callback callback) {
try {
// do some work
callback.onComplete();
} catch (Exception e) {
callback.onError(e);
}
}
}