如题,我们先抽象出被观察者和观察者
/** *抽象观察者 */ abstract class obServer { protected String name; public obServer(String name) { this.name = name; } protected SubJect subJect; //更新接口 public abstract void updata(); //不在观察 public abstract void dontLook(SubJect subJect); }
/** *抽象被观察者 */ abstract class SubJect{ //所有观察者 private List<obServer> obServerList=new ArrayList<>(); //状态 private int state; public int getState() { return state; } public void setState(int state) { this.state = state; } //添加观察者 public void attach(obServer obServer){ obServerList.add(obServer); System.out.println("新增观察者:"+obServer.name); } //删除观察者 public void deletObServer(obServer obServer){ obServerList.remove(obServer); System.out.println("移除观察者:"+obServer.name); } //更新观察者 public void updateObServer(){ for (obServer o:obServerList) { o.updata(); } } }
有一档电视节目来当实体(被观察者)
class TVPlay extends SubJect{ private String theTVSet; public String getTheTVSet() { return theTVSet; } public void setTheTVSet(String theTVSet) { this.theTVSet = theTVSet; } public void play(){ System.out.println("电视剧开播了!今日节目:"+ theTVSet); //通知观察者 updateObServer(); } }
人实体来充当观察者
class People extends obServer{ public People(String name) { super(name); } @Override public void updata() { System.out.println(name+"收到电视剧开播通知"); } @Override public void dontLook(SubJect subJect) { subJect.deletObServer(this); } }
执行时,被观察者会检查所有观察者,去调用play下发通知
public static void main(String[] args) { TVPlay tvPlay = new TVPlay(); People man = new People("男人"); People woman = new People("女人"); tvPlay.attach(man); tvPlay.attach(woman); tvPlay.setTheTVSet("宫锁心玉"); tvPlay.play(); System.out.println("新的一期开始了!"); System.out.println("上次不好看,男人取消了观察"); man.dontLook(tvPlay); tvPlay.setTheTVSet("宫锁心玉2"); tvPlay.play(); }