首页 > 代码库 > java观察者模式

java观察者模式

观察者设定一个观察目标,根据观察目标的变化,观察者采取相应的应对行为---观察者模式

 

 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观察者模式