Java 观察者模式,也可以叫做Publish/Subscribe模式。
简单理解,多个Observer可以订阅一个Subject,如果Subject有什么更新,通知Observer。
package cn.true123.observer;
import java.util.ArrayList;
import java.util.List;
public class TestObserver {
interface IObserver {
void update(String text);
}
interface ISubject {
public void register(IObserver iObserver);
public void unRegister(IObserver iObserver);
public void notifyObservers();
public void setValue(String value);
}
class Observer1 implements IObserver {
@Override
public void update(String text) {
System.out.println("Observer1 receive the message: " + text);
}
}
class Observer2 implements IObserver {
@Override
public void update(String text) {
System.out.println("Observer2 receive the message: " + text);
}
}
class Subject implements ISubject {
private List<IObserver> observers = new ArrayList<>();
private String value;
@Override
public void register(IObserver iObserver) {
observers.add(iObserver);
}
@Override
public void unRegister(IObserver iObserver) {
if (observers.contains(iObserver)) {
observers.remove(iObserver);
}
}
@Override
public void notifyObservers() {
for (IObserver iObserver : observers) {
iObserver.update(value);
}
}
@Override
public void setValue(String value) {
this.value = value;
}
}
public static void main(String[] args) {
TestObserver testObserver = new TestObserver();
ISubject subject = testObserver.new Subject();
IObserver iObserver1 = testObserver.new Observer1();
IObserver iObserver2 = testObserver.new Observer2();
subject.register(iObserver1);
subject.register(iObserver2);
subject.setValue("news updated");
subject.notifyObservers();
}
}
结果:
Observer1 receive the message: news updated
Observer2 receive the message: news updated