五:觀察者模式

以下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);


    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容