Observer design pattern example

Observale class
-----------------------------------------------

package com.anil.observable;

import java.util.Observable;

public class DataObject extends Observable {

private String txt;

public DataObject(String s) {
this.txt=s;
}

public String getTxt() {
return txt;
}

public void setTxt(String txt) {
this.txt = txt;
setChanged();
}

}
------------------------------------------------
Observer classes
------------------------------------------------
package com.anil.observer;

import java.util.Observable;
import java.util.Observer;

import com.anil.observable.DataObject;

public class FirstObserver implements Observer{

@Override
public void update(Observable o, Object arg) {

System.out.println("FirstObserver----"+((DataObject)o).getTxt());
}

}
-----------------------------------------------------------------------------------
package com.anil.observer;

import java.util.Observable;
import java.util.Observer;

import com.anil.observable.DataObject;

public class SecondObserver implements Observer {

@Override
public void update(Observable o, Object arg) {

System.out.println("SecondObserver----"+((DataObject)o).getTxt());

}

}
-----------------------------------------------------------------------------------
test classes
-----------------------------------------------------------------------------------
package com.anil.data;

import com.anil.observable.DataObject;
import com.anil.observer.FirstObserver;
import com.anil.observer.SecondObserver;

public class ObserverTest {

public static void main(String[] args) {

DataObject db = new DataObject("anil");
FirstObserver fo=new FirstObserver();
SecondObserver so=new SecondObserver();
db.addObserver(fo);
db.addObserver(so);
db.setTxt("Data Updated");
db.notifyObservers();

}

No comments:

Post a Comment