import java.util.ArrayList; import java.util.Iterator; /* 抽象观察者类 */ abstract class Observer { public abstract void update(); } /* 抽象被观察主题类 */ abstract class Subject{ private ArrayList obs_list = new ArrayList(); public void attach(Observer obs) { obs_list.add(obs); } public void Detach(Observer obs) { obs_list.remove(obs); } public void notifyObs() { for (Iterator iter = obs_list.iterator(); iter.hasNext();) { Observer obs = (Observer) iter.next(); obs.update(); } } } /* 具体观察者类 */ class ConcreteObserver extends Observer { private String obs_name; private ConcreteSubject cc_subj; public ConcreteObserver(String obs_name, ConcreteSubject cc_subj) { this.obs_name = obs_name; this.cc_subj = cc_subj; } public void update() { if (cc_subj.getStatus() == 1) { System.out.println("Boss come back, " + obs_name + " turn off screen!"); } else { System.out.println("Boss go out, " + obs_name + " turn on screen!"); } } } /* 具体观察主题类 */ class ConcreteSubject extends Subject { private int status; public ConcreteSubject(int status) { this.status = status; } public int getStatus() { return status; } public void setStatus(int status) { if (status != this.status) { this.status = status; super.notifyObs(); } } } public class Observer_Test{ public static void main(String[] args) { ConcreteSubject cc_sub = new ConcreteSubject(0); ConcreteObserver cc_obs1 = new ConcreteObserver("E1", cc_sub); ConcreteObserver cc_obs2 = new ConcreteObserver("E2", cc_sub); ConcreteObserver cc_obs3 = new ConcreteObserver("E3", cc_sub); cc_sub.attach(cc_obs1); cc_sub.attach(cc_obs2); cc_sub.attach(cc_obs3); cc_sub.setStatus(1); //status changed to 1 System.out.println("---------------------------------------"); cc_sub.setStatus(0); //status changed to 0 } }
result:
Boss come back, E1 turn off screen!
Boss come back, E2 turn off screen!
Boss come back, E3 turn off screen!
---------------------------------------
Boss go out, E1 turn on screen!
Boss go out, E2 turn on screen!
Boss go out, E3 turn on screen!
时间: 2024-10-25 14:10:55