被观察者接口:
public interface IMonitorSubject {
public void addListener(IMonitorListener listener);
public void notifyListener(JobCtrl implJobCtrl);
}
观察者接口:
public interface IMonitorListener {
public void statistical(JobCtrl implJobCtrl);
}
被观察者实现:
public class JobSubject implements IMonitorSubject {
private final CopyOnWriteArraySet<IMonitorListener> monitorListener = new CopyOnWriteArraySet<>();
@Override
public void addListener(IMonitorListener listener) {
monitorListener.add(listener);
}
@Override
public void notifyListener(JobCtrl implJobCtrl) {
for (IMonitorListener listener : monitorListener) {
try {
listener.statistical(implJobCtrl);
} catch (Exception e) {
Log.e("statistic jobs error.");
Log.e(e);
}
}
}
}
观察者实现:
public class JobListener implements IMonitorListener {
private JobListener() {
}
static class SingletonHolder {
static JobListener instance = new JobListener();
}
public static JobListener getInstance() {
return SingletonHolder.instance;
}
@Override
public void statistical(JobCtrl implJobCtrl) {
//do some things.
}
}
调用者:
public class JobMonitor{
private IMonitorSubject subject = new JobSubject();
private JobCtrl implJobCtrl= new JobCtrl();
public JobMonitor(){
subject.addListener(JobListener.getInstance());
}
@Override
public static void main(String[] args) {
Log.i("JobMonitorBuilder start[schedule]-----");
subject.notifyListener(implJobCtrl);
Log.i("JobMonitorBuilder end[schedule]-----");
return null;
}
}
时间: 2024-09-27 19:41:24