观察者模式(发布-订阅模式)
用途:可用于拦截过滤器
消息推送接口:
public interface Subject {
//添加订阅者
void addObserver(Observer observer);
//移除订阅者
void removeObserver(Observer observer);
//通知订阅者
void notifyObservers(String message);
}
消息推送实现着:
public class ConcreteSubject implements Subject{
//订阅者集合
ArrayList<Observer> observers = new ArrayList<>();
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
订阅者接口
public interface Observer {
void update(String message);
}
订阅者1
public class ObserverOne implements Observer{
@Override
public void update(String message) {
System.out.println("ObserverOne"+message);
}
}
订阅者2
public class ObserverTwo implements Observer{
@Override
public void update(String message) {
System.out.println("ObserverTwo"+message);
}
}
测试:
public class Tes {
public static void main(String[] args) {
ConcreteSubject concreteSubject = new ConcreteSubject();
concreteSubject.addObserver(new ObserverOne());
concreteSubject.addObserver(new ObserverTwo());
concreteSubject.notifyObservers("hello world");
}
}