The observer mode defines one-to-multiple dependencies between objects, so that one or more observer objects can observe a topic object. When the status of the topic object changes, the system can notify all observer objects dependent on this object so that the observer objects can be automatically updated!
In the observer mode, the observed object is often referred to as the [target] or [subject] (subject), and the dependent object is called The Observer (observer ).
The company's system reminds me of this pattern. There is only one artist in the company, and many projects require an artist. It is a headache for the artist to ask for leave, because the department manager wants to call the artist to notify the company's more than a dozen project managers one by one.
This mode is often used:
For example, the system event processing method also uses this mode, which is the queen of the design mode, haha.
For heterogeneous systems, MQ is the most frequently used now, and shares.
Setting up the observer mode is now very simple for Java!
Step 1: Create subject (inherit observable)
Package CN. yangcai. subject; import Java. util. observable; public class artdesignersubject extends observable {public void message (Object arg0) {If (true) {// determines whether to trigger the notification super. setchanged () ;}yyobservers (arg0 );}}
Step 2: Create an observer (inheriting observer)
Package CN. yangcai. observer; import Java. util. observable; import Java. util. observer; public class yangcaiobserver implements observer {public void Update (observable arg0, object arg1) {If (arg1 instanceof string) {system. out. println ("artist" + arg0 + "Tell Project Manager Yang cai:" + arg1 );}}}
Step 3: Call
Package CN. yangcai; import CN. yangcai. observer. yangruiobserver; import CN. yangcai. observer. yangcaiobserver; import CN. yangcai. subject. artdesignersubject; public class test {public static void main (string [] ARGs) {// 1. create subjectartdesignersubject subject = new artdesignersubject (); // 2. create an observer and add yangcaiobserver = new yangcaiobserver (); yangruiobserver = new yangruiobserver (); s Ubject. addobserver (yangcaiobserver); // Add to list subject. addobserver (yangruiobserver); // Add to list // 3. send notification subject. Message ("I'm on vacation! "); Subject. Message (" I'm back on vacation! ");}}
Output:
The artist CN. yangcai. Subject. artdesignersubject @ affc70 told the Project Manager Yang Rui: I'm on vacation! The artist CN. yangcai. Subject. artdesignersubject @ affc70 told the Project Manager Yang cai: I'm on vacation! The artist CN. yangcai. Subject. artdesignersubject @ affc70 told the Project Manager Yang Rui: I'm back on vacation! The artist CN. yangcai. Subject. artdesignersubject @ affc70 told the Project Manager Yang cai: I'm back on vacation!
CodeDownload: http://download.csdn.net/detail/ycyangcai/4198632