以下demo 含義:
如果小孩兒哭了,父母需要做出反應(yīng),所以父母需要監(jiān)視小孩哭的動作。
比如有個app,父母在app訂閱,小孩哭這個動作會推送一個消息。父母接收到了這個消息作出反應(yīng)。
@Data
public class Event {
private int msg;
}
public class Child {
public void cry(int message) {
System.out.println("小孩醒了");
Event event = new Event();
event.setMsg(message);
// 小孩哭了向app推送消息
ObserverListenerUtil.pushEvent(event);
}
}
// 監(jiān)聽者接口
public interface ObserverListener {
void doSomeThing(Event event);
}
// 父親監(jiān)聽后實現(xiàn)
public class Dad implements ObserverListener {
@Override
public void doSomeThing(Event event) {
if (event.getMsg() == 1) {
System.out.println("dad feeds");
}
}
}
// 母親監(jiān)聽后實現(xiàn)
public class Mom implements ObserverListener {
@Override
public void doSomeThing(Event event) {
if (event.getMsg() == 2) {
System.out.println("mom feeds");
}
}
}
// app ,收集所有訂閱消息的監(jiān)聽者
public class ObserverListenerUtil {
static List<ObserverListener> listenerList = Lists.newArrayList();
public static void register(ObserverListener observerListener) {
listenerList.add(observerListener);
}
// 向每個監(jiān)聽者推送消息
public static void pushEvent(Event event) {
listenerList.stream().forEach(item -> item.doSomeThing(event));
}
}
//測試demo
public class ObserverDemo {
public static void main(String[] args) {
ObserverListenerUtil.register(new Dad());
ObserverListenerUtil.register(new Mom());
Child child = new Child();
child.cry(1);
System.out.println("----");
child.cry(2);
child.cry(1);
}
}