观察者模式
消息发布者找到所有监听者,各个发布事件,实际工作中可用于找到所有实现摸个接口的实现类,统一调用各自的实现方法
public class ObserverTest
{
public static void main(String[] args) {
Subject subject = new Subject();
Listen1 listen1 = new Listen1();
subject.addObserver(listen1);
Listen2 listen2 = new Listen2();
subject.addObserver(listen2);
subject.publishMsg("消息通知 ");
}
}
class Subject
{
// 容器
private List<Listener> container = new ArrayList<>();
// add
public void addObserver(Listener listener) {
container.add(listener);
}
// remove
public void remove(Listener listener) {
container.remove(listener);
}
//发布消息
public void publishMsg(Object object) {
for (Listener item : container) {
item.send(object);
}
}
}
interface Listener
{
void send(Object object);
}
class Listen1 implements Listener
{
@Override
public void send(Object object) {
System.out.println(" 观察者1执行: " + object);
}
}
class Listen2 implements Listener
{
@Override
public void send(Object object) {
System.out.println(" 观察者2执行:" + object);
}
}