你的位置:首页 > ASP.net教程

[ASP.net教程]ObserverPattern(观察者模式)

import java.util.ArrayList;import java.util.List;/** * 观察者模式 * @author TMAC-J * 牵一发而动全身来形容观察者模式在合适不过了 * 分为拉模式和推模式,这里不详细说了 */public class ObserverPattern {    interface IObserved{        void addObserver(IObserver observer);        void removeObserver(IObserver observer);        void notifyObservers();   }     public class Observed implements IObserved{    private List<IObserver> observers = new ArrayList<IObserver>();        @Override    public void addObserver(IObserver observer) {      observers.add(observer);          }    @Override    public void removeObserver(IObserver observer) {      observers.remove(observer);    }    @Override    public void notifyObservers() {      for(IObserver observer:observers){        observer.update();      }    }      }    interface IObserver{        void update();      }    public class Observer implements IObserver{    @Override    public void update() {      System.out.println("do update...");    }      }    public void test(){    IObserved observed = new Observed();    IObserver observer = new Observer();    observed.addObserver(observer);    observed.notifyObservers();  }  }