I think we're looking for an observer pattern. The concept of the observer pattern is http://warmz.tistory.com/entry/Observer-Pattern-%EC%98%B5%EC%A0%80%EB%B2%84-%ED%8C%A8%ED%84%B4 It's well explained here, so please refer to it.
This is a sample code.
import java.util.*;
interface HelloListener {
void someoneSaidHello();
}
class Initiater {
private List<HelloListener> listeners = new ArrayList<HelloListener>();
public void addListener(HelloListener toAdd) {
listeners.add(toAdd);
}
public void sayHello() {
System.out.println("Hello!!");
for (HelloListener hl : listeners)
hl.someoneSaidHello();
}
}
class Responder implements HelloListener {
@Override
public void someoneSaidHello() {
System.out.println("Hello there...");
}
}
class Test {
public static void main(String[] args) {
Initiater initiater = new Initiater();
Responder responder = new Responder();
initiater.addListener(responder);
Initiator.sayHello(); // When someone says "Hello!!" other objects answer "Hello there..."
}
}
© 2024 OneMinuteCode. All rights reserved.