The class teacher came to the observer mode, event delegation and other Java implementation---if you do not understand, read this article, will certainly understand

Source: Internet
Author: User

The homeroom teacher is coming! Small A to Small B said: "Today is really laughing dead, our Class A classmate in the careful time to watch the NBA game, the class teacher caught a positive." The head teacher's face is green, haha, really laughed at my death. Small B said: "Ah, how can you classmates dare to watch TV in class?" Small a said: "No, they through these boys often watch the game when they study." One of the girls in our class was sitting in the front row, and the boys were giving her a little gift or something. The head teacher came, the girl went to the notice to knock on the table. "Little B said:" Well. That's OK. Then why would anyone get caught today? "Small A said:" This is because the teacher came to the time, the girl went to the toilet. As a result, a comic-reading boy was not caught, and the boy who watched the NBA game was caught. The phones have been confiscated! "Little B said:" Well. The scene you're talking about reminds me of a design pattern called the Observer pattern. Why don't you tell me about it? "Small a vomiting blood, fall down ...
Observer pattern let's look at the definition of the Observer pattern: The Observer pattern defines a one-to-many dependency, allowing 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. In the above scene, the Observer refers to the hard-pressed students, and the subject of the listener is the evil head teacher, the class teacher came, notify all the classmates, then all the students to automatically update themselves, watching the NBA game stop to see the book, read the comic also stop to read. What do you think? is not fried chicken image, the following we use code to implement the above scenes in the things that happen:
Import java.util.*;//is responsible for monitoring the female classmate class Girlclassmate {private String action; Front desk secretary found the situation//to her to send Guoli male students private arraylist<nbawatcher> observers = new arraylist<nbawatcher> ();//Increase, Just a few classmates asked her to help us, just add several objects in the collection public void Attach (Nbawatcher observer) {OBSERVERS.ADD (Observer);} Remove object from Care object public void Delete (Nbawatcher observer) {OBSERVERS.REMOVE (Observer);} Notice to watch every student in the NBA, the class teacher came!public void Notify () {for (Nbawatcher observer:observers) {Observer. Update ();}} public void Setaction (String action) {this.action = action;} Public String getaction () {return action;}}          See the NBA classmate class Nbawatcher {private String name;   The name of the classmate private girlclassmate Wodi; Front row undercover mmpublic void Update () {//TODO auto-generated method StubSystem.out.println (wodi.getaction () + name + "Don't watch the game, keep on learning!" ");} Public Nbawatcher (String name, Girlclassmate wodi) {this.name = Name;this.wodi = Wodi;}}     public class MainClass {public static void main (string[] args) {girlclassmate MM = new Girlclassmate (); Foreground mm Object NbawAtcher DIAOSI1 = new Nbawatcher ("Cock wire 1", MM);   Look at the stock colleague 1NbaWatcher Diaosi2 = new Nbawatcher ("Stud 2", MM); Look at the stock of colleague 1//two Dick colleague added into the foreground mm of Care object list Mm.attach (DIAOSI1); Mm. Attach (DIAOSI2);//Front desk mm found the boss back Mm.setaction ("Class teacher back!") ");//notify each colleague in the care list, the boss is Back mm.notify ();}}
Output Result:
The head teacher is back! Dick Silk 1 Don't look at the game, keep on studying! The head teacher is back! Dick Silk 2 Don't look at the game, keep on studying!
How do you write this code? Definitely not good! The front row female classmate object relies on the concrete to see the NBA schoolmate object, but the NBA classmate object relies on the front row female classmate object. Then this creates a two-way coupling relationship. In a piece of code, it's not good to have a coupling over high. In the professional case of dependency reversal, it is: the concrete should depend on the abstraction, the abstraction should not depend on the concrete. According to this principle, we will look at the observer of the NBA game, the observer of the comic, and so on, an abstract observer class. And whether the front-row mm notifier, or the head teacher this notifier is a notifier, so can also be abstracted as a notifier class. The code after the improvement is as follows:
Import java.util.*;//Notice, may be the head teacher himself, may also be the front row female classmate abstract class Notifier {private arraylist<observer> observers = new Arraylist<observer> ();p ublic void Attach (Observer Observer) {observers.add (Observer);} public void Delete (Observer Observer) {observers.remove (Observer);} Notify the students list of each colleague, the class teacher came to public void Notify () {for (Observer observer:observers) {Observer. Update ();}} Abstract public void Setaction (string action), abstract public String getaction ();}         Class Boss extends Notifier{private String action; What the notifier found//The boss found the case public void setaction (String action) {this.action = action;} Public String getaction () {return action;}}         Class Girlclassmate extends Notifier{private String action; Case found by the notifier//foreground mm found condition public void setaction (String action) {this.action = action;} Public String getaction () {return action;}}          Observer Master zu abstract class Observer {protected String name;        The classmate's name protected Notifier Notifier; Event notifier abstract void Update ();p ublic Observer (String nAme, Notifier Notifier) {this.name = Name;this.notifier = Notifier;}} See NBA colleague Class Nbawatcher extends Observer{public nbawatcher (String name, Notifier Notifier) {super (name, Notifier);// Todo auto-generated constructor stub}public void Update () {//TODO auto-generated method StubSystem.out.println (notifier . getaction () + name + "Don't watch the game, keep on learning!" ");}} Watch the World Cup colleague class Comicreader extends Observer{public comicreader (String name, Notifier Notifier) {super (name, Notifier); /Todo auto-generated constructor stub}public void Update () {//Todo auto-generated method StubSystem.out.println (notifie R.getaction () + name + "Don't look at comics, continue learning");}}     public class MainClass {public static void main (string[] args) {Notifier Tuhao = new Boss ();   The notifier replaced the head teacher himself observer DIAOSI1 = new Nbawatcher ("Unlucky cock silk 1", tuhao);   Watch the NBA classmate Observer Diaosi2 = new Comicreader ("Lucky cock 2", tuhao); Watch the NBA classmates//Add two stud colleagues to the foreground mm//tuhao in the list of care objects.  Attach (DIAOSI1); Unlucky cock Silk 1, did not add into the boss's care list, so was caught Tuhao. Attach (DIAOSI2);//Front desk mm found the boss back Tuhao.setaction ("head teacher I come back!")");//notify the attention list of each colleague, the boss came back Tuhao. Notify ();}}
The deficiency of the Observer pattern "the abstract notifier in the code of the machine above is still dependent on the abstract observer, in case there is no abstract observer, it will not be able to complete the function!" And you write the code above, so the object updates are the same action. What if my object update is different? For example, watching the NBA game heard the head teacher came to go to the toilet, and read the comic to hear the class teacher came to continue reading. How should the code be written? Little A, rubbing sleepy's sleepy eyes, asked in doubt. Little B said: "I go, I thought you were asleep!" Oh, you're listening! I'm so happy. Let's use a kind of thing called "event entrust" to solve this problem ha! "Small A said:" I drop a god, what is the event entrusted AH? "Observer pattern Improvement-reflection version event delegate Small B said:" You do not worry first Ah! Let's see what we can do with that! "In the code, we go beyond the abstract observer class and the client decides which observer to notify." Ps:java is not like C # inside the delegation, so I use the reflection in Java implementation, see the following code.
Import Java.util.*;import java.lang.reflect.*;//Notice, may be the boss, may also be the front office Secretary abstract class Notifier {protected Method Update; Abstract public void Setaction (String action), abstract public void Notify (Object object);}         Class Boss extends Notifier{private String action; What the notifier found//The boss found the case public void setaction (String action) {this.action = action;} public void Notify (Object object) {if (Update! = null) {try {Update.invoke (object, action);} catch (Exception e) {e.prints Tacktrace ();}}}         Class Girlclassmate extends Notifier{private String action;          The notifier found the public Method Update; Reflection Event//boss found case public void setaction (String action) {this.action = action;} public void Notify (Object object) {if (Update! = null) {try {Update.invoke (object, action);} catch (Exception e) {e.prints Tacktrace ();}}}          Look at the stock colleague Class Nbawatcher {protected String name;        The colleague's name protected Notifier Notifier; Front desk Undercover mmpublic nbawatcher (String name, Notifier Notifier) {this.name = Name;this.notifier = NotIfier;} public void Closenbawatcher (String action) {//TODO auto-generated method StubSystem.out.println (Action + name + "Don't watch the game, go on. Learning ");}}          Watch the World Cup colleague class Comicreader {protected String name;        The colleague's name protected Notifier Notifier; Front desk Undercover mmpublic comicreader (String name, Notifier Notifier) {this.name = Name;this.notifier = Notifier;} public void Closecomicreader (String action) {//TODO auto-generated method StubSystem.out.println (Action + name + "Don't look at comics. Continued learning ");}} public class MainClass {public static void main (string[] args) {Notifier Tuhao = new Boss ();  Nbawatcher DIAOSI1 = new Nbawatcher ("Unlucky cock silk 1", tuhao);  Comicreader Diaosi2 = new Comicreader ("Lucky cock silk 2", tuhao); Tuhao.setaction ("Class teacher I come back!") "); try {Tuhao. Update = Diaosi1.getclass (). GetMethod ("Closenbawatcher", new class[] {string.class}); catch (Nosuchmethodexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (SecurityException e) {//T ODO auto-generated catch Blocke.printstacktrace ();} Tuhao. Notify ((Object) DiaOSI1); try {Tuhao. Update = Diaosi2.getclass (). GetMethod ("Closecomicreader", new class[] {string.class}); catch (Nosuchmethodexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (SecurityException e) {//T ODO auto-generated catch Blocke.printstacktrace ();} Tuhao. Notify ((Object) DIAOSI2);}}
Launch implementation entrusted Core:
Protected Method update;if (Update! = null) {try {Update.invoke (object, action);} catch (Exception e) {e.printstacktrace () ;}} try {Tuhao. Update = Diaosi2.getclass (). GetMethod ("Closecomicreader", new class[] {string.class}); catch (Nosuchmethodexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (SecurityException e) {//T ODO auto-generated catch Blocke.printstacktrace ();} Tuhao. Notify ((Object) DIAOSI2);
As you can see from the upper-right code, reflection enables different methods to be called depending on the class. Just like in C #, a delegate can carry multiple methods, all of which are recalled at once. Feel, also a bit like the C language inside the hook function.
Successor small a said: Wow! Small B Hello, oh, I really understand the observation mode Ah, another launch mode really good use! Small B said: O (∩_∩) o haha ~ you learn something good! In fact, thank the author of the blood to finish, I, laughed ~~~~~~~ you all understand!



The class teacher came to the observer mode, event delegation and other Java implementation---if you do not understand, read this article, will certainly understand

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.