假设我有一个捆绑包想要向所有听众广播信息。考虑到我正在使用MyComponent
消耗 0..n的声明性服务ComponentListeners
,我会有这样的事情:
public class MyComponent {
private List<ComponentListener> listeners;
private String data;
public MyComponent() {
listeners = new ArrayList<>();
}
// Someone else will call this
public void updateData(String newData) {
data = newData;
notifyAll(data);
}
// Broadcasts the data to all listeners
private void notifyAll(String data) {
for (ComponentListener listener : listeners) {
listener.updateData(data);
}
}
// Declarative Service binding methods
public void bindComponentListener(ComponentListener cl) {
listeners.add(cl);
}
public void unbindComponentListener(ComponentListener cl) {
listeners.remove(cl);
}
}
我的问题是:
- 推荐使用 0..n 基数吗?我发现的唯一示例来自Apache Felix 教程,与上面的教程类似。
- 观察者/可观察方法是否被认为是 OSGi 中的良好实践?
- 如果我想通知所有听众,我应该
listener.updateData(data);
为每个听众调用不同的线程,对吗?这样,我确保将同时通知所有听众。