1 ImportJava.util.Map;2 ImportJava.util.HashMap;3 ImportJava.util.Observer;4 Importjava.util.Observable;5 6 //Student Class (Student) can be observed after inheriting observable7 classStudentextendsobservable{8 //Properties9 PrivateString name;Ten Private BooleanIssleep =false; One Private BooleanIslate =false; A //constructor Function - PublicStudent () {} - PublicStudent (String name) { the This. Name =name; - } - //Sleep Behavior - Public voidsleep () { +SYSTEM.OUT.PRINTLN (name + "is sleeping"); -Issleep =true; + setchanged (); ANotifyobservers ("Sleep"); at - } - //Late Behavior - Public voidlate () { -SYSTEM.OUT.PRINTLN (name + "was lated"); -Islate =true; in setchanged (); -Notifyobservers ("Late"); to } + } - //Teacher Class (Teacher) implements observer interface becomes observer the classTeacherImplementsobserver{ * //parameter arg as key, the response triggered by this parameter is stored in the map as value $ Privatemap<string,string> info =NewHashmap<string,string>();Panax Notoginseng PublicTeacher () { -Info.put ("Sleep", "wakeup!wakeup!"); theInfo.put ("Late", "Come in."); + } A //to add a key-value pair the Public BooleanAddsay (String k,string v) { + returnInfo.put (k,v) = =NULL?false:true; - } $ @Override $ Public voidUpdate (Observable o,object arg) { -String say =Info.get (ARG); - if(Say = =NULL){ the return; - }WuyiSystem.out.println ("Teacher:" +say); the } - } Wu //class Teacher (CLASSHEAD) realizes observer interface becomes observer - classClassheadImplementsobserver{ About Privatemap<string,string> info =NewHashmap<string,string>(); $ PublicClasshead () { -Info.put ("Sleep", "Gooutwashbaface"); -Info.put ("Late", "cleantheroom!"); - } A Public BooleanAddsay (String k,string v) { + returnInfo.put (k,v) = =NULL?false:true; the } - @Override $ Public voidUpdate (Observable o,object arg) { theString say =Info.get (ARG); the if(Say = =NULL){ the return; the } -System.out.println ("Classhead:" +say); in } the } the Public classobserverdemo{ About Public Static voidMain (string[] arguments) { theStudent Tom =NewStudent ("Tom"); theTom.addobserver (Newclasshead ()); theTom.addobserver (NewTeacher ()); + -System.out.println ("with" +tom.countobservers () + "Observer in the observation of Tom"); the tom.sleep ();Bayi tom.late (); the } the}
Design Pattern 01 Observer pattern (Java)