public class Watched
{
Watcher watcherList;
public synchronized void addWatcher(Watcher w)
{
if (w == null)
{
return;
}
watcherList =WatcherMultiCaster.add(watcherList,w);
}
public synchronized void removeWatcher(Watcher s) {
if (s == null) {
return;
}
watcherList = WatcherMultiCaster.remove(watcherList, s);
}
public void processAction(String msg){
Watcher w = watcherList;
if(w!=null){
w.action(msg);
}
}
}
//---------------------------------------------------------------------------------------------------------
public interface Watcher //观察者接口
{
public void action(String msg);
}
//---------------------------------------------------------------------------------------------------------
public class WatcherMultiCaster implements Watcher //铸造器
{
protected final Object a,b;
protected WatcherMultiCaster(Object a,Object b){
this.a = a;
this.b = b;
}
public static Watcher add(Watcher a,Watcher b){
return (Watcher) addInternal(a,b);
}
public static Watcher remove(Watcher w,Watcher oldw){
return (Watcher)removeInternal(w,oldw);
}
protected static Object addInternal(Object a,Object b){
if (a == null) return b;
if (b == null) return a;
return new WatcherMultiCaster(a, b);
}
protected static Object removeInternal(Object w, Object oldw)
{
if (w == oldw || w == null) {
return null;
} else if (w instanceof WatcherMultiCaster) {
return ((WatcherMultiCaster)w).remove(oldw);
} else {
return w;
}
}
private Object remove(Object oldw)
{
if (oldw == a) return b;
if (oldw == b) return a;
Object a2 = removeInternal(a, oldw);
Object b2 = removeInternal(b, oldw);
if (a2 == a && b2 == b) {
return this;
}
return addInternal(a2, b2);
}
@Override
public void action(String msg)
{
((Watcher)a).action(msg);
((Watcher)b).action(msg);
}
}
//---------------------------------------------------------------------------------------------------------
public class WatcherA implements Watcher
{
@Override
public void action(String msg)
{
System.out.println("WatcherA recived:"+msg);
}
}
public class WatcherB implements Watcher
{
@Override
public void action(String msg)
{
System.out.println("WatcherB recived: "+msg);
}
}
public class WatcherC implements Watcher
{
@Override
public void action(String msg)
{
System.out.println("WatcherC recived:"+msg);
}
}
//---------------------------------------------------------------------------------------------------------
public class ObserverTest
{
/**
* @param args
*/
public static void main(String[] args)
{
Watched watched = new Watched();
WatcherA wa = new WatcherA();
WatcherB wb = new WatcherB();
WatcherC wc = new WatcherC();
watched.addWatcher(wa);
watched.addWatcher(wb);
watched.addWatcher(wc);
watched.processAction("Stand up!");
watched.removeWatcher(wb);
watched.processAction("Sit down");
watched.addWatcher(new WatcherC());
watched.processAction("Sing!");
}
}