EventBus is Guava's event processing mechanism and an elegant implementation of the observer pattern (producer/consumer programming model) in the design pattern. EventBus is a very elegant and simple solution for event listening and publish-subscribe patterns. We don't have to create complex class and interface hierarchies.
The Observer pattern is one of the more commonly used design patterns. Although sometimes it is not necessarily called this name in the specific code, for example, it is called Listener, but the pattern is this pattern. Implementing an Observer manually is not a complicated matter. Just because this design pattern is so commonly used, Java put it in the JDK: Observable and Observer. They have been there since JDK 1.0. To some extent, it simplifies the development of the Observer pattern, at least we no longer have to manually maintain our own Observer list. However, as mentioned before, the Observer in the JDK has been there since 1.0. Until Java 7, it has not changed much. Even the parameters of the notification are still of type Object. You know, Java 5 already has generics. Java 5 was a massive syntax overhaul, and many libraries have redesigned their APIs since then to make them simpler and easier to use. Of course, those libraries that don't respond will probably become obsolete. This is why knowledge updating is discussed here. Today, for ordinary applications, what should we do if we want to use the Observer pattern? The answer is Guava's EventBus.
Basic usage of EventBus:
After using Guava, if you want to subscribe to messages, you no longer need to inherit the specified interface. You only need to add the @Subscribe annotation to the specified method. The code is as follows:
Message encapsulation class:
[code]public class TestEvent { private final int message; public TestEvent(int message) { this.message = message; System.out.println("event message:"+message); } public int getMessage() { return message; } }
Message acceptance class:
[code]public class EventListener { public int lastMessage = 0; @Subscribe public void listen(TestEvent event) { lastMessage = event.getMessage(); System.out.println("Message:"+lastMessage); } public int getLastMessage() { return lastMessage; } }
Test class and output results:
[code]public class TestEventBus { @Test public void testReceiveEvent() throws Exception { EventBus eventBus = new EventBus("test"); EventListener listener = new EventListener(); eventBus.register(listener); eventBus.post(new TestEvent(200)); eventBus.post(new TestEvent(300)); eventBus.post(new TestEvent(400)); System.out.println("LastMessage:"+listener.getLastMessage()); ; } } //输出信息 event message:200 Message:200 event message:300 Message:300 event message:400 Message:400 LastMessage:400
Use of MultiListener :
You only need to add the @Subscribe annotation to the method to subscribe to the message to subscribe to multiple messages. The code is as follows:
[code]public class MultipleListener { public Integer lastInteger; public Long lastLong; @Subscribe public void listenInteger(Integer event) { lastInteger = event; System.out.println("event Integer:"+lastInteger); } @Subscribe public void listenLong(Long event) { lastLong = event; System.out.println("event Long:"+lastLong); } public Integer getLastInteger() { return lastInteger; } public Long getLastLong() { return lastLong; } }
[code]public class TestMultipleEvents { @Test public void testMultipleEvents() throws Exception { EventBus eventBus = new EventBus("test"); MultipleListener multiListener = new MultipleListener(); eventBus.register(multiListener); eventBus.post(new Integer(100)); eventBus.post(new Integer(200)); eventBus.post(new Integer(300)); eventBus.post(new Long(800)); eventBus.post(new Long(800990)); eventBus.post(new Long(800882934)); System.out.println("LastInteger:"+multiListener.getLastInteger()); System.out.println("LastLong:"+multiListener.getLastLong()); } } //输出信息 event Integer:100 event Integer:200 event Integer:300 event Long:800 event Long:800990 event Long:800882934 LastInteger:300 LastLong:800882934
Dead Event:
If the messages sent by EventBus are not of concern to subscribers, it is called a Dead Event. The example is as follows
[code]public class DeadEventListener { boolean notDelivered = false; @Subscribe public void listen(DeadEvent event) { notDelivered = true; } public boolean isNotDelivered() { return notDelivered; } }
[code]public class DeadEventListener { boolean notDelivered = false; @Subscribe public void listen(DeadEvent event) { notDelivered = true; } public boolean isNotDelivered() { return notDelivered; } }
Description: If there are no message subscribers listening to the message, EventBus will send the DeadEvent message. At this time, we can record this status through log.
Event inheritance:
If Listener A listens to Event A, and Event A has a subclass Event B, then Listener A will receive Event A and B messages at the same time. The example is as follows:
Listener class:
[code]public class NumberListener { private Number lastMessage; @Subscribe public void listen(Number integer) { lastMessage = integer; System.out.println("Message:"+lastMessage); } public Number getLastMessage() { return lastMessage; } } public class IntegerListener { private Integer lastMessage; @Subscribe public void listen(Integer integer) { lastMessage = integer; System.out.println("Message:"+lastMessage); } public Integer getLastMessage() { return lastMessage; } }
[code]public class TestEventsFromSubclass { @Test public void testEventsFromSubclass() throws Exception { EventBus eventBus = new EventBus("test"); IntegerListener integerListener = new IntegerListener(); NumberListener numberListener = new NumberListener(); eventBus.register(integerListener); eventBus.register(numberListener); eventBus.post(new Integer(100)); System.out.println("integerListener message:"+integerListener.getLastMessage()); System.out.println("numberListener message:"+numberListener.getLastMessage()); eventBus.post(new Long(200L)); System.out.println("integerListener message:"+integerListener.getLastMessage()); System.out.println("numberListener message:"+numberListener.getLastMessage()); } } //输出类 Message:100 Message:100 integerListener message:100 numberListener message:100 Message:200 integerListener message:100 numberListener message:200
Description: In this method, we see that the first event (new integer (100)) is received by two listeners, but the second (new long (200 l)) can only be reached by NumberListener as an integer - there is no event created for this type. You can use this feature to create more general listeners that listen to a broad set of events and more detailed listeners that listen to specific special events.
A comprehensive instance:
[code]public class UserThread extends Thread { private Socket connection; private EventBus channel; private BufferedReader in; private PrintWriter out; public UserThread(Socket connection, EventBus channel) { this.connection = connection; this.channel = channel; try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); out = new PrintWriter(connection.getOutputStream(), true); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } @Subscribe public void recieveMessage(String message) { if (out != null) { out.println(message); System.out.println("recieveMessage:"+message); } } @Override public void run() { try { String input; while ((input = in.readLine()) != null) { channel.post(input); } } catch (IOException e) { e.printStackTrace(); } //reached eof channel.unregister(this); try { connection.close(); } catch (IOException e) { e.printStackTrace(); } in = null; out = null; } }
[code]mport java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import com.google.common.eventbus.EventBus; public class EventBusChat { public static void main(String[] args) { EventBus channel = new EventBus(); ServerSocket socket; try { socket = new ServerSocket(4444); while (true) { Socket connection = socket.accept(); UserThread newUser = new UserThread(connection, channel); channel.register(newUser); newUser.start(); } } catch (IOException e) { e.printStackTrace(); } } }
Description: Use the telnet command to log in: telnet 127.0.0.1 4444. If you connect to multiple instances you will see that any messages sent are transmitted to other instances
The above is the content of Java-Class Library-Guava-EventBus. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!