Publishing news:BreakingNewsEmailSubscriber received news:BreakingNewsContent:An earthquake hit the city!MobileAppSubscriber received news:BreakingNewsWebPageSubscriber received news:BreakingNewsContent:An earthquake hit the city!
importjava.util.ArrayList;importjava.util.List;// 首先,我们定义Observer接口和Subject接口interfaceObserver{voidupdate(String message);}interfaceSubject{voidregisterObserver(Observer o);voidremoveObserver(Observer o);voidnotifyObservers(String message);}// 实现Player类作为SubjectclassPlayerimplementsSubject{privateList<Observer> observers;privateint healthPoints;publicPlayer(int initialHealth){this.observers =newArrayList<>();this.healthPoints = initialHealth;}@OverridepublicvoidregisterObserver(Observer o){observers.add(o);}@OverridepublicvoidremoveObserver(Observer o){observers.remove(o);}@OverridepublicvoidnotifyObservers(String message){for(Observer observer : observers){observer.update(message);}}publicvoidtakeDamage(int damage){healthPoints -= damage;if(healthPoints <0){healthPoints =0;}notifyObservers("Player took "+ damage +" damage. Remaining health: "+ healthPoints);}publicintgetHealthPoints(){return healthPoints;}publicbooleanisAlive(){return healthPoints >0;}}// 创建HUDDisplay和GameLog作为ObserverclassHUDDisplayimplementsObserver{@Overridepublicvoidupdate(String message){System.out.println("HUD: "+ message);}}classGameLogimplementsObserver{@Overridepublicvoidupdate(String message){System.out.println("Log: "+ message);}}// 创建一个Enemy类,它负责攻击玩家classEnemy{privateString name;privateint attackPower;publicEnemy(String name,int attackPower){this.name = name;this.attackPower = attackPower;}publicvoidattack(Player target){int damage =this.attackPower;target.takeDamage(damage);System.out.println(this.name +" attacked the player!");}}publicclassGameTest{publicstaticvoidmain(String[] args){// 创建玩家对象Player player =newPlayer(100);// 创建HUD显示和游戏日志对象,并注册为观察者HUDDisplay hudDisplay =newHUDDisplay();GameLog gameLog =newGameLog();player.registerObserver(hudDisplay);player.registerObserver(gameLog);// 创建敌人对象Enemy enemy =newEnemy("Goblin",20);// 敌人攻击玩家enemy.attack(player);// 检查玩家是否存活,并显示相关信息if(player.isAlive()){System.out.println("Player is still alive with "+ player.getHealthPoints()+" health points.");}else{System.out.println("Player has been defeated!");}}}
将看到如下输出:
HUD:Player took 20damage. Remaining health:80Log:Player took 20damage. Remaining health:80Goblin attacked the player!Player is still alive with80 health points.