The observer sets an observation target, and according to the observed target, the observer takes the corresponding action ---The observer pattern .
1 //Player Class2 Public classPlayer {3 4 PrivateString name;5 PrivateTeam t;6 7 PublicPlayer (String name) {8 This. Name =name;9 }Ten One PublicString GetName () { A returnname; - } - the Public voidSetteam (Team t) { - This. t=T; - } - + //If the player is attacked, call the game Center for help - Public voidbeattacked (Controller c) { +SYSTEM.OUT.PRINTLN (name + "be attacked ~ speed to aid ~"); A C.noticeother (t,name); at - } - - //to help a teammate. - Public voidHelp () { -System.out.println ("Hang on!" "+ name +" Come also ~ ~ ~); in } - } to + //Squad category - Importjava.util.ArrayList; the Importjava.util.List; * $ Public classTeam {Panax Notoginseng -@SuppressWarnings ("Unused") the PrivateString name; + A PrivateList<player> players =NewArraylist<player>(); the + PublicTeam (String name) { - This. Name =name; $SYSTEM.OUT.PRINTLN (name + "Team formation success!") "); $ } - - Public voidjoin (Player p) { the This. Players.add (p); -P.setteam ( This);Wuyi } the - Public voidHelp (String name) { Wu for(Player player:players) { - if(!player.getname (). Equals (name)) { About player.help (); $ } - } - } - A } + the //Game Center - Public classController { $ the Public voidNoticeother (Team t,string name) { the t.help (name); the } the - } in the the // About Public classObservertestdemo { the the Public Static voidMain (string[] args) { the +Controller C =NewController (); - theTeam T =NewTeam ("Jin Yong");Bayi thePlayer P1 =NewPlayer ("Make Fox Punch"); the T.join (p1); -Player P2 =NewPlayer ("Zhang Mowgli"); - T.join (p2); thePlayer P3 =NewPlayer ("Oriental Undefeated"); the T.join (p3); thePlayer P4 =NewPlayer ("Yang Too"); the T.join (p4); - the p1.beattacked (c); the } the 94}
Java Watcher pattern