Guava——EventBus

EventBus是Guava的事件處理機制,是設(shè)計模式中的觀察者模式(生產(chǎn)/消費者編程模型)的優(yōu)雅實現(xiàn)冤馏。對于事件監(jiān)聽和發(fā)布訂閱模式帆竹,EventBus是一個非常優(yōu)雅和簡單解決方案豹障,我們不用創(chuàng)建復(fù)雜的類和接口層次結(jié)構(gòu)。

Guide

For Listeners

To listen for a specific flavor of event (say, a CustomerChangeEvent)...

  • ...in traditional Java events: implement an interface defined with the event -- such as CustomerChangeEventListener.
  • ...with EventBus: create a method that accepts CustomerChangeEvent as its sole argument, and mark it with the @Subscribe annotation.

To register your listener methods with the event producers...

  • ...in traditional Java events: pass your object to each producer'sregisterCustomerChangeEventListener method. These methods are rarely defined in common interfaces, so in addition to knowing every possible producer, you must also know its type.
  • ...with EventBus: pass your object to the EventBus.register(Object) method on an EventBus. You'll need to make sure that your object shares an EventBus instance with the event producers.

To listen for a common event supertype (such as EventObject or Object)...

  • ...in traditional Java events: not easy.
  • ...with EventBus: events are automatically dispatched to listeners of any supertype, allowing listeners for interface types or "wildcard listeners" for Object.

To listen for and detect events that were dispatched without listeners...

  • ...in traditional Java events: add code to each event-dispatching method (perhaps using AOP).
  • ...with EventBus: subscribe to DeadEvent. The EventBus will notify you of any events that were posted but not delivered. (Handy for debugging.)

For Producers

To keep track of listeners to your events...

  • ...in traditional Java events: write code to manage a list of listeners to your object, including synchronization, or use a utility class like EventListenerList.
  • ...with EventBus: EventBus does this for you.

To dispatch an event to listeners...

  • ...in traditional Java events: write a method to dispatch events to each event listener, including error isolation and (if desired) asynchronicity.
  • ...with EventBus: pass the event object to an EventBus's EventBus.post(Object)method.

Glossary

The EventBus system and code use the following terms to discuss event distribution:

Event Any object that may be posted to a bus.
Subscribing The act of registering a listener with an EventBus, so that its handler methods will receive events.
Listener An object that wishes to receive events, by exposing handler methods.
Handler method A public method that the EventBus should use to deliver posted events. Handler methods are marked by the @Subscribe annotation.
Posting an event Making the event available to any listeners through the EventBus.

例子

public class TGuavaEventBus {

    // 消息? 事件腊嗡?
    static class TestEvent{
        private final int message;
        public TestEvent(int message) {
            this.message = message;
        }
        public int getMessage() {
            return message;
        }
    }

    static class TestEvent2{
        private final String message;
        public TestEvent2(String message) {
            this.message = message;
        }
        public String getMessage() {
            return message;
        }
    }

    static class EventListener {
        private String name;
        public int intMsg = 0;

        public EventListener(String aname){
            name = aname;
        }
        @Subscribe
        public void listenInt(TestEvent event) {
            intMsg = event.getMessage();
            System.out.println(name + " receive a Message:"+ intMsg);
        }
        @Subscribe
        public void listenInt2(TestEvent event) {
            intMsg = event.getMessage();
            System.out.println(name + "receive b Message:"+ intMsg);
        }

    }

    static class EventListener2 {
        private String name;
        public int intMsg = 0;
        public String strMsg;

        public EventListener2(String aname){
            name = aname;
        }

        // 消息的接收舷手,是按照消息類型判斷的拧簸,與方法名無關(guān)
        @Subscribe
        public void listen(TestEvent event) {
            intMsg = event.getMessage();
            System.out.println(name + "receive int Message:"+intMsg);
        }
        @Subscribe
        public void listenStr(TestEvent2 event) {
            strMsg = event.getMessage();
            System.out.println(name + " receive str Message:"+strMsg);
        }
    }

    static class Productor1{
        private final int num;
        private final String message;
        public Productor1(int anum, String amessage){
            num = anum;
            message = amessage;
        }

        public void doBusi1(){
            System.out.println("-----------doBusi1---"+message);
            eventBus1.post(new TestEvent(num));
            eventBus1.post(new TestEvent2(message));
            System.out.println("-----------doBusi1---"+message);
        }

        public void doBusi2(){
            System.out.println("-----------doBusi2---"+message);
            eventBus2.post(new TestEvent(num));
            eventBus2.post(new TestEvent2(message));
            System.out.println("-----------doBusi2---"+message);

        }

        public void doBusi3(){
            System.out.println("-----------doBusi3---"+message);
            eventBus1.post(new TestEvent(num));
            System.out.println("----11------");

            eventBus2.post(new TestEvent(num));
            System.out.println("----22------");

            eventBus1.post(new TestEvent2(message));
            System.out.println("----33------");

            eventBus2.post(new TestEvent2(message));
            System.out.println("-----------doBusi3---"+message);
        }

    }
    private static EventBus eventBus1 = new EventBus("eventBus_1");
    private static EventBus eventBus2 = new EventBus("eventBus_2");

    public static void testReceiveEvent(){

        Productor1 pdt1 = new Productor1(1, "product_1");
        Productor1 pdt2 = new Productor1(2, "product_2");
        Productor1 pdt3 = new Productor1(3, "product_3");

        EventListener listener1_1 = new EventListener("listen1_1");
        EventListener listener1_2 = new EventListener("listen1_2");

        eventBus1.register(listener1_1);
        eventBus1.register(listener1_2);

        EventListener2 listener2_1 = new EventListener2("listen2_1");
        eventBus2.register(listener2_1);

        pdt1.doBusi1();
        pdt2.doBusi2();
        pdt3.doBusi3();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市男窟,隨后出現(xiàn)的幾起案子盆赤,更是在濱河造成了極大的恐慌,老刑警劉巖歉眷,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件牺六,死亡現(xiàn)場離奇詭異,居然都是意外死亡汗捡,警方通過查閱死者的電腦和手機淑际,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來凉唐,“玉大人庸追,你說我怎么就攤上這事√ù眩” “怎么了淡溯?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長簿训。 經(jīng)常有香客問我咱娶,道長米间,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任膘侮,我火速辦了婚禮屈糊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘琼了。我一直安慰自己逻锐,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布雕薪。 她就那樣靜靜地躺著昧诱,像睡著了一般。 火紅的嫁衣襯著肌膚如雪所袁。 梳的紋絲不亂的頭發(fā)上盏档,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天,我揣著相機與錄音燥爷,去河邊找鬼蜈亩。 笑死,一個胖子當(dāng)著我的面吹牛前翎,可吹牛的內(nèi)容都是我干的稚配。 我是一名探鬼主播,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼鱼填,長吁一口氣:“原來是場噩夢啊……” “哼药有!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起苹丸,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤愤惰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后赘理,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體宦言,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年商模,在試婚紗的時候發(fā)現(xiàn)自己被綠了奠旺。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,773評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡施流,死狀恐怖响疚,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情瞪醋,我是刑警寧澤忿晕,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站银受,受9級特大地震影響践盼,放射性物質(zhì)發(fā)生泄漏鸦采。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一咕幻、第九天 我趴在偏房一處隱蔽的房頂上張望渔伯。 院中可真熱鬧,春花似錦肄程、人聲如沸锣吼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽吐限。三九已至鲜侥,卻和暖如春褂始,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背描函。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工崎苗, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人舀寓。 一個月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓胆数,卻偏偏與公主長得像,于是被迫代替她去往敵國和親互墓。 傳聞我的和親對象是個殘疾皇子必尼,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,689評論 2 354

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,324評論 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    網(wǎng)事_79a3閱讀 12,060評論 3 20
  • 又一周過去,一日班主任正式上崗也有三周了篡撵,今天利用放學(xué)前的一段時間判莉,十個一日班主任走上講臺,接受全班同學(xué)的評定育谬。你...
    謝意閱讀 193評論 0 0
  • 經(jīng)常聽人說到一句話“但行好事膛檀,莫問前程”锰镀,今天終于對這句話有了更深的理解。 早上從會議室簽完合同出來的時候咖刃,有一點...
    孤獨的人晚回家閱讀 2,566評論 2 6
  • 好像是昨天還在笑橙哥死的早泳炉,橙哥笑我日的少,明天鄰桌就不是橙哥了嚎杨。 不和向治橙一個班我玩狼人殺都不知道該投誰了花鹅。 ...
    長歌先生閱讀 394評論 0 0