不定长函参的Java观察者模式更新数据传递
import java.util.LinkedList;
/**
* 抽象被观察者。
*
* @param <T>
*/
public abstract class Subject<T> {
private LinkedList<Observer> observers;
public Subject() {
observers = new LinkedList<>();
}
public Subject getSubject() {
return this;
}
public void registerObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObserver(T... t) {
for (Observer observer : observers) {
observer.update(getSubject(), t);
}
}
}
/**
* 抽象观察者。
* @param <T>
*/
public interface Observer<T> {
void update(Subject subject, T... t);
}
public class State extends Subject {
@Override
public Subject getSubject() {
return this;
}
}
public class ObserverImpl implements Observer<Object> {
@Override
public void update(Subject subject, Object... objects) {
StringBuffer sb = new StringBuffer();
for (Object o : objects) {
sb.append(o.toString() + ",");
}
System.out.println("观察到更新:" + sb.toString());
}
}
测试:
Subject subject = new State();
Observer observer = new ObserverImpl();
subject.registerObserver(observer);
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
subject.notifyObserver((i++)+"",(i++)+"");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
输出:
观察到更新:0,1,
观察到更新:2,3,
观察到更新:4,5,
观察到更新:6,7,
观察到更新:8,9,
观察到更新:10,11,