看《java編程思想》裏面提到的觀察者模式,看了沒看懂,後來在網上查了一下。寫了下面的程序,但願幫助你們理解。java
package com.test; import java.util.Observable; import java.util.Observer; /** * 評委1 * */ class Judges1 implements Observer { @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub System.out.println(arg); System.out.println("Judges1的評分是9.8分!"); } } /** * 評委2 * */ class Judges2 implements Observer { @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub System.out.println(arg); System.out.println("Judges2的評分是9.5分!"); } } /** * 表演者 * */ public class Participants extends Observable { //表演結果 public void resultShow(String str) { if (true) { super.setChanged(); } notifyObservers(str); } public static void main(String[] args) { // 建立一個被觀察者 Participants participants = new Participants(); // 建立兩個觀察者 Judges1 Judges1 = new Judges1(); Judges2 judges2 = new Judges2(); // 把兩個觀察者加到被觀察者列表中 participants.addObserver(Judges1); participants.addObserver(judges2); participants.resultShow("請評委評分!"); } }