1. 程式人生 > >java觀察者模式

java觀察者模式

sta ray equals system clas tde team oid 東方

觀察者設定一個觀察目標,根據觀察目標的變化,觀察者采取相應的應對行為---觀察者模式

 1 //玩家類
 2 public class Player {
 3     
 4     private String name;
 5     private Team t;
 6     
 7     public Player(String name){
 8         this.name = name;
 9     }
10     
11     public String getName(){
12         return name;
13     }
14     
15
public void setTeam(Team t){ 16 this.t= t; 17 } 18 19 //如果玩家被攻擊,通知遊戲中心進行呼救 20 public void beAttacked(Controller c){ 21 System.out.println(name + "被攻擊~速來援助~"); 22 c.noticeOther(t,name); 23 24 } 25 26 //用來援助隊友的 27 public void help(){ 28 System.out.println("挺住!" + name + "來也~~~");
29 } 30 } 31 32 //戰隊類 33 import java.util.ArrayList; 34 import java.util.List; 35 36 public class Team { 37 38 @SuppressWarnings("unused") 39 private String name; 40 41 private List<Player> players = new ArrayList<Player>(); 42 43 public Team(String name){
44 this.name = name; 45 System.out.println(name + "戰隊組建成功!"); 46 } 47 48 public void join(Player p){ 49 this.players.add(p); 50 p.setTeam(this); 51 } 52 53 public void help(String name) { 54 for (Player player : players) { 55 if (!player.getName().equals(name)) { 56 player.help(); 57 } 58 } 59 } 60 61 } 62 63 //遊戲中心 64 public class Controller { 65 66 public void noticeOther(Team t,String name){ 67 t.help(name); 68 } 69 70 } 71 72 73 // 74 public class ObserverTestDemo { 75 76 public static void main(String[] args) { 77 78 Controller c = new Controller(); 79 80 Team t = new Team("金庸"); 81 82 Player p1 = new Player("令狐沖"); 83 t.join(p1); 84 Player p2 = new Player("張無忌"); 85 t.join(p2); 86 Player p3 = new Player("東方不敗 "); 87 t.join(p3); 88 Player p4 = new Player("楊過"); 89 t.join(p4); 90 91 p1.beAttacked(c); 92 } 93 94 }

java觀察者模式