我的观察者模式

package pattern;

import java.util.Map;

public interface Observable {
  public void update(Observe o,Map map);  

}

package pattern;

import java.util.Map;

public interface Observe {
public void addObservable(Observable observable);
public void removeObservable(Observable observable);
public void change(Map map);
}

 

 

 

package pattern;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ObserveDefaultImp implements Observe{
private List<Observable> observables=new ArrayList();
//多线程共享,需要为方法以及变做同步
  public synchronized void addObservable(Observable observable) {
  // TODO Auto-generated method stub
   observables.add(observable);
 }

 private void notifyObservable(Map map) {
  //通知观察着并传递其消息,Map包含被观察者的状态改变类别以及观察着作出回应所需要的辅助信息
  // TODO Auto-generated method stub
  Iterator it=observables.iterator();
  while(it.hasNext()){
   ((Observable) it.next()).update(this,map);
  }
 }

 public synchronized void removeObservable(Observable observable) {
  // TODO Auto-generated method stub
  observables.remove(observable);
 }

 public void change(Map map) {
  // TODO Auto-generated method stub
  notifyObservable(map);
  
 }

}

 

 

package pattern;

import java.util.Map;

public class ObservableDefaultImp implements Observable{

 public void update(Observe o, Map map) {
  // TODO Auto-generated method stub
  System.out.print("o has changed!");
  
 }

}

你可能感兴趣的:(java,多线程)