In the process of writing code, we need to implement a function: When executing a certain logic, we want to be able to do other logical processing. The most brutal method is to directly rely on other modules and invoke the corresponding function or method of the module. However, doing so poses some problems.
- The modules are dependent on each other and have high coupling degree. For example, the following orders are submitted for payment and some other processing, such as e-mail and other operations. This may be the case with the relevant code. You can see that the order module relies on payment services and User services.
- Maintenance difficulties. Because of the interdependence between modules, you need to modify the source code of the SubmitOrder method when you need to modify the order logic, and some times you may not be able to modify it. Furthermore, if there is more than one such logic, the modification may involve multiple operations.
public class Orderpage {private Paymentservice paymentservice; Private UserService UserService; public void SubmitOrder () {Integer userId = 1; BigDecimal amount = Bigdecimal.ten; Paymentservice.dopayment (userId, amount); Userservice.registerpayment (userId, amount); }}public class Paymentservice {private Mailservice mailservice; public void Dopayment (Integer userId, BigDecimal amount) {//do payment ... MAILSERVICE.SENDP Aymentemail (userId, amount); }}public class UserService {public String getemailaddress (Integer userId) {return ' [EMAIL PR Otected] "; } public void Registerpayment (Integer userId, BigDecimal amount) {//register Payment in Da Tabase ...}} public class Mailservice {private UserService userservice; PublIC void Sendpaymentemail (Integer userId, BigDecimal amount) {String EmailAddress = Userservice.getemailadd Ress (USERID); Send email ...}}
First, the Observer pattern
Sometimes referred to as the Publish/subscribe pattern, the Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. This subject object notifies all observer objects when the state changes, enabling them to automatically update themselves.
The observer pattern is decoupled, and when the object changes, the observer is notified and processed accordingly. In order logic, define the subject of the order being observed by multiple observers, and notify all observers when the action of the immediate order occurs. It is then processed by each observer. Depending on the implementation of the observer pattern, the above logic can be changed to the following code:
Interface Orderlistener {public void Onsubmitorder (Integer userId, BigDecimal amount);} public class Orderpage {private list<orderlistener> orderlisteners=new arraylist<orderlistener> ();p ublic void SubmitOrder () {Integer userId = 1; BigDecimal amount = bigdecimal.ten;for (Orderlistener orderlistener:orderlisteners) {Orderlistener.onsubmitorder ( UserId, amount);}} public void Addorderlistener (Orderlistener orderlistener) {this.orderListeners.add (Orderlistener);}} Class Paymentservice implements Orderlistener {private mailservice mailservice;public void Dopayment (Integer userId, BigDecimal amount) {//Do Payment...mailservice.sendpaymentemail (userId, amount);} @Overridepublic void Onsubmitorder (Integer userId, BigDecimal amount) {dopayment (userId, amount);}} Class UserService implements Orderlistener {public String getemailaddress (Integer userId) {return ' [email Protected] ";} public void Registerpayment (Integer userId, BigDecimal amount) {//Register payment in database ...} @Overridepublic void Onsubmitorder (Integer userid, BigDecimal amount) {registerpayment (userId, amount);}} Class Mailservice {private UserService userservice;public void Sendpaymentemail (Integer userId, BigDecimal amount) { String EmailAddress = userservice.getemailaddress (userId);//Send email ...}}
As you can see, the Orderlistener interface is defined first, and there is a Onsubmitorder method in the interface. The interface was implemented in the original implementation of Payservice and UserService. A orderlistener list is maintained in Orderpage that invokes the Onsubmitorder method of all listeners when the order is submitted. You can see that the order logic for this implementation is not directly dependent on the payment module and the user module. The main program notifies you by adding a listener
public static void Main (string[] args) { paymentservice paymentservice=new paymentservice (); UserService userservice=new UserService (); Orderpage orderpage=new orderpage (); Orderpage.addorderlistener (paymentservice); Orderpage.addorderlistener (UserService);}
Ii. Guava Eventbus (graceful implementation of listener mode)
Although the listener pattern is decoupled from the source code, there are some deficiencies.
- Relevant modules need to implement the corresponding interface;
- You need to actively invoke the relevant AddListener method to set up the listener.
- A listener intelligently listens to an operation.
Eventbus is the implementation of guava for listener mode, which is very simple to use. Using Eventbus to implement listener mode requires only three steps.
- Declare the event callback method by annotating @subscribe;
- Call Eventbus's Register method to register the listener;
- The Post method is used to trigger the event;
The order logic is implemented via the Eventbus event bus, presumably as follows:
public class Orderpage {public static Eventbus Eventbus = new Eventbus ();p ublic void SubmitOrder () {Integer userId = 1; BigDecimal amount = Bigdecimal.ten;eventbus.post (new payevent (UserId, amount));}} Class Paymentservice {private Mailservice mailservice; @Subscribepublic void Dopayment (Payevent payevent) {//do payment. .. Mailservice.sendpaymentemail (Payevent.getuserid (), Payevent.getamount ());}} Class UserService {public String getemailaddress (Integer userId) {return ' [email protected] ';} @Subscribepublic void Registerpayment (Payevent payevent) {//Register payment in Database ...}} Class Payevent {Private integer userid;private BigDecimal amount;public payevent (Integer userId, BigDecimal amount) {}pub Lic Integer getUserId () {return userId;} Public BigDecimal Getamount () {return amount;}} public static void Main (string[] args) {paymentservice paymentservice=new paymentservice (); UserService userservice=new UserService (); Orderpage orderpage=new orderpage (); OrderpaGe.eventBus.register (Paymentservice); OrderPage.eventBus.register (UserService);}
To implement listener mode, you need to call Eventbus's Register method to register and use the @subscribe annotation on the method that needs to handle the event. Finally, the event can be published via Eventbus. Using Event bus, you do not need to define a specific interface, do not need to actively add listeners;
Third, event subscription
Eventbus registering the class that handles the corresponding event through the Register method
public void Register (object object) { multimap<class<?>, eventsubscriber> methodsinlistener = Finder.findallsubscribers (object); Subscribersbytypelock.writelock (). Lock (); try { subscribersbytype.putall (methodsinlistener); } finally { subscribersbytypelock.writelock (). Unlock (); } }
At its core is findallsubscribers, which finds all the methods in the instance that have subscribe annotations and saves them. Returned is a Multimap < class<?>,eventsubscriber> type, where class is the event type, Eventsubsciber contains the class instance and the method that handles the event specifically. Multimap guarantees that an event can be handled by multiple listeners.
public multimap<class<?>, eventsubscriber> findallsubscribers (Object listener) { Multimap<class <?>, eventsubscriber> Methodsinlistener = Hashmultimap.create (); Class<?> clazz = Listener.getclass (); For (Method method:getannotatedmethods (clazz)) { class<?>[] parametertypes = Method.getparametertypes (); Class<?> eventtype = parametertypes[0]; Eventsubscriber subscriber = Makesubscriber (listener, method); Methodsinlistener.put (EventType, subscriber); } return methodsinlistener; }
Publish Events
Eventbus publishes events through the Post method, first finding the event that needs to be handled through the event type: The event itself and its parent class. The subscriber that handles the event is removed from the cache of the event subscription based on the event type and enqueued. Finally, the data in the queue is processed.
public void Post (Object event) { set<class<?>> dispatchtypes = FlattenHierarchy (Event.getclass ()); Boolean dispatched = false; for (class<?> eventtype:dispatchtypes) { subscribersbytypelock.readlock (). Lock (); try { set<eventsubscriber> wrappers = Subscribersbytype.get (EventType); if (!wrappers.isempty ()) { dispatched = true; for (Eventsubscriber wrapper:wrappers) { enqueueevent (event, wrapper);}}} finally { Subscribersbytypelock.readlock (). Unlock (); } } if (!dispatched &&!) ( Event instanceof Deadevent) { post (new Deadevent (this, event)); } Dispatchqueuedevents (); }
Java Event Bus