Implement publish and subscribe using observer and observable pattern.
package com.tools.publishsubscribe;
import java.util.Observable;
public class ManagedWork extends Observable{
public void send(){
setChanged();
notifyObservers() ;
}
}
package com.tools.publishsubscribe;
import java.util.Observable;
import java.util.Observer;
public class ManagedWorkMonitor implements Observer {
public void update(Observable o, Object arg) {
System.out.println("Observed by ManagedWorkMonitor -- " + o.countObservers()) ;
}
}
package com.tools.publishsubscribe;
public class ManagedWorkDemo {
private ManagedWork work ;
private ManagedWorkMonitor workMonitor ;
private ManagedWorkMonitor2 workMonitor2 ;
public ManagedWorkDemo(){
work = new ManagedWork() ;
workMonitor = new ManagedWorkMonitor() ;
workMonitor2 = new ManagedWorkMonitor2() ;
work.addObserver(workMonitor);
work.addObserver(workMonitor2);
}
public static void main(String str[]){
ManagedWorkDemo demo = new ManagedWorkDemo() ;
demo.send() ;
}
private void send(){
work.send() ;
}
public String getName() {
return "Message" ;
}
}
package com.tools.publishsubscribe;
import java.util.Observable;
import java.util.Observer;
public class ManagedWorkMonitor2 implements Observer {
public void update(Observable o, Object arg) {
System.out.println("Observed by ManagedWorkMonitor2 -- " + o.countObservers() ) ;
}
}
No comments:
Post a Comment