观察者模式实现
package com.wh.observer;
public interface Watchers {
void update(Object o);
}
package com.wh.observer;
public interface Watcheds {
void addWatcher(Watchers watcher);
void removeWatcher(Watchers watcher);
void notifyWatchers(Object o);
}
package com.wh.observer.demo;
import com.wh.observer.Watcheds;
import com.wh.observer.Watchers;
import java.util.ArrayList;
import java.util.List;
public class TestBean implements Watcheds {
private List<Watchers> list = new ArrayList<Watchers>();
@Override
public void addWatcher(Watchers watcher) {
list.add(watcher);
}
@Override
public void removeWatcher(Watchers watcher) {
list.remove(watcher);
}
@Override
public void notifyWatchers(Object o) {
for (Watchers watcher : list) {
watcher.update(o);
}
}
}
package com.wh.observer.demo;
import com.wh.observer.Watchers;
public class TestWatcher implements Watchers {
@Override
public void update(Object o) {
System.out.println("---" + o);
}
}
package com.wh.observer.demo;
import com.wh.observer.Watcheds;
import com.wh.observer.Watchers;
public class Test {
public static void main(String[] args) {
Watcheds watched = new TestBean();
Watchers watcher = new TestWatcher();
Watchers watcher2 = new TestWatcher();
watched.addWatcher(watcher);
watched.removeWatcher(watcher2);
watched.notifyWatchers("测试");
}
}