In the blog, there is a subscription function, when you subscribe, when bloggers publish a new blog, you can receive the message. How is this implemented? Is there a thread in the background that doesn't stop polling? If this is the case, obviously too much resources, if the blog when publishing, find all Subscribers, and then loop to send the message to subscribers, this will be more humane. This is the observer pattern, the observer pattern has two objects: Blogger, subscriber. When the reader is subscribed, it will put the reader information in a queue to facilitate the blog in the main cloth to cycle the column and send messages. With this analysis, the code comes out:
First subscribers:
Public interface Observers {public void execute (String s);}
public class Observer implements observers{@Overridepublic void execute (String s) {System.out.println (s);}}
And then publish the blog Center:
Public interface Stations {public void Addobserver (observers observers);p ublic void Removeobserver (observers observers) ;p ublic void Notityobserver (String s);}
Public class Station implements Stations{private list<observers> List = new arraylist<observers> (); Overridepublic void Addobserver (observers observers) {List.add (observers);} @Overridepublic void Removeobserver (observers observers) {List.remove (observers);} @Overridepublic void Notityobserver (String s) {for (observers observers:list) {Observers.execute (s);}}}
Execute:
public class Executor {public static void main (string[] args) {Stations station = new station (); Station.addobserver (New Ob Server ()); Station.addobserver (new Observer ()); Station.addobserver (new Observer ()); Station.addobserver (new Observer ()); Station.notityobserver ("Please use Zson");}}
This is the basic implementation of the whole observer pattern.
Application Scenarios and Functions:
Use under 1.PUB/SUB (Publish/subscribe)
2. If there are two business modules, if you need to notify each other, you can use this method to decouple
Implementation of the Java watcher pattern