用途:可用于拦截过滤器
消息推送接口:
java
public interface Subject {
//添加订阅者
void addObserver(Observer observer);
//移除订阅者
void removeObserver(Observer observer);
//通知订阅者
void notifyObservers(String message);
}
消息推送实现着:
java
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);
}
}
}
订阅者接口
java
public interface Observer {
void update(String message);
}
订阅者1
java
public class ObserverOne implements Observer{
@Override
public void update(String message) {
System.out.println("ObserverOne"+message);
}
}
订阅者2
java
public class ObserverTwo implements Observer{
@Override
public void update(String message) {
System.out.println("ObserverTwo"+message);
}
}
测试:
java
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");
}
}