//被观察者接口,有添加观察者对象,唤醒所有观察者等方法申明。 public interface ISubject { public void setName(String name); public String getName(); public void addObserver(IObserver o); public void notifyAllObserver(); }
import java.util.*; public class Subject implements ISubject{ private String name; List<IObserver> observers = new ArrayList<IObserver>(); public Subject(){} public Subject(String name){ this.name=name; } public String getName(){ return this.name; } public void setName(String name){ this.name=name; } public void addObserver(IObserver o){ observers.add(o); } public void notifyAllObserver(){ for(int i=0;i<observers.size();i++){ observers.get(i).showInfo(); } } }
//观察者接口。 public interface IObserver { public void showInfo(); }
public class Observer implements IObserver{ private ISubject sjtref = null; public void setRef(ISubject sjt){ this.sjtref=sjt; } public Observer(ISubject sjtref){ super(); this.sjtref=sjtref; } public void showInfo(){ System.out.println("Observering:"+sjtref.getName()); } }
public class ObserverMain { public static void main(String args[]){ //新建被观察对象 ISubject subject = new Subject("Shen,Ziping"); //新建观察者对象 IObserver observer1 = new Observer(subject); //注册 subject.addObserver(observer1); //唤醒观察者 subject.notifyAllObserver(); } }
|