java觀察者模式

來源:互聯網
上載者:User

標籤:use   other   oid   res   beat   this   port   std   play   

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

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.