关闭

观察者模式

372人阅读 评论(0) 收藏 举报
分类:

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

                                ========         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();
    }
}











0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:45054次
    • 积分:673
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:121篇
    • 译文:0篇
    • 评论:0条