论坛首页 Java企业应用论坛

hand first 设计模式 --观察者模式

浏览 1514 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-06-18   最后修改:2009-06-18
利用java api 实行观察者模式

1.推模式(主题将一样数据发生给所有的观察者)

主题
public class WeacherData extends Observable {
	
	private int data1;
	
	private int data2;
	
	
	public void update(){
	    this.setChanged();
	    //这里将WeacherData 对象传递给观察者属于推模式
             this.notifyObservers(this);
	}

	public int getData1() {
		return data1;
	}

    public int getData2() {
		return data2;
	}
    
    public void setData(int data1,int data2){
    	this.data1 = data1;
    	this.data2 = data2;
    }

}


观察者
public class ClientData implements Observer {
	Observable obser;
	private int data1;
	
	private int data2;
	
	
    public 	ClientData(Observable obser){
    	this.obser = obser;
    	obser.addObserver(this);
    	
    }

	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
		if(o instanceof WeacherData ){
			WeacherData w = (WeacherData)arg;
			//data = w.getData1();
			data1 = w.getData1();
			data2 = w.getData2();
			display();
		}

	}
	
	public void display(){
		System.out.println("data1 is "+data1+" and data2 is "+data2);
	}

}



2.拉模式(不同的观察者有选择的获取想要的数据)
public class WeacherData extends Observable {
	
	private int data1;
	
	private int data2;
	
	
	public void update(){
	    this.setChanged();
	    //没有传递数据给观察者
             this.notifyObservers();
	}

	public int getData1() {
		return data1;
	}

    public int getData2() {
		return data2;
	}
    
    public void setData(int data1,int data2){
    	this.data1 = data1;
    	this.data2 = data2;
    }

}



public class ClientData implements Observer {
	Observable obser;
	private int data1;
	
	private int data2;
	
	
    public 	ClientData(Observable obser){
    	this.obser = obser;
    	obser.addObserver(this);
    	
    }

	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
		if(o instanceof WeacherData ){
			WeacherData w = (WeacherData)o;
			 //观察都根据需求,得到想要的数据
                            data1 = w.getData1();
			//data2 = w.getData2();
			display();
		}

	}
	
	public void display(){
		System.out.println("data1 is "+data1+" and data2 is "+data2);
	}

}


测试

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		WeacherData data = new WeacherData();
		
		ClientData client = new ClientData(data);
		
        data.setData(1, 2);

	}

}



注意观察都显示结果是无序的.

缺点:
主题类不能再继承其他类了.

设计原则

为交互对象之间松耦合设计

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics