观察者模式

转载 2013年12月05日 16:30:04

 =============设计模式之禅========= 

                                ========         first          ============

/** 
 * 观察者
 */
public interface Observer {
     /**
     * 观察到行动后自己动起来
     */
    public void update(String context);
}

/**
 * 
 * 被观察者
 */
public interface Observable {
     public void addObserver(Observer observer);
     public void deleteObserver(Observer observer);
     public void notifyObservers(String context);
}

public class HanFeizi implements Observable {
    private List<Observer> observerList = new ArrayList<Observer>();
    
	@Override
	public void addObserver(Observer observer) { 
		this.observerList.add(observer);

	}

	@Override
	public void deleteObserver(Observer observer) { 
		this.observerList.remove(observer);

	}

	@Override
	public void notifyObservers(String context) { 
		for(Observer observer:observerList){
			observer.update(context);
		}

	}
	
	public void haveBreakfast(){
		this.notifyObservers("韩非子在吃饭");
	}
    public void haveFun(){
    	this.notifyObservers("韩非子在娱乐");
    }
}

public class Lisi implements Observer {

	@Override
	public void update(String context) { 
		System.out.println("李斯观察到  : "+ context);

	}

}

public class Client { 
	public static void main(String[] args) { 
          HanFeizi hanfei = new HanFeizi();
          Lisi lisi = new Lisi();
          hanfei.addObserver(lisi);
          hanfei.haveBreakfast();
	} 
}

      ==========    second   =========


public class HanFeizi extends Observable {
     public void haveBreakfast(){ 
    	 super.setChanged();
    	 super.notifyObservers("韩非子在吃饭");
     }
     
     public void haveFunt(){ 
    	 super.setChanged();
    	 super.notifyObservers("韩非子在娱乐");
     }
}


public class Lisi implements Observer { 
	@Override
	public void update(Observable observable, Object context) {
		 System.out.println("李斯观察到  :"+ context.toString()); 
	} 
}

public class Client {
    public static  void main(String args[]){
    	Lisi lisi = new Lisi();
    	HanFeizi hanfei = new HanFeizi();
    	hanfei.addObserver(lisi);
    	hanfei.haveBreakfast();
    }
}











内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:观察者模式
举报原因:
原因补充:

(最多只允许输入30个字)