public class Observer {
static class UploadFile {
static ArrayList<UploadListener> mListeners = new ArrayList<>();
public static void setListener(UploadListener listener) {
if (mListeners != null) mListeners.add(listener);
}
public static void removeListener(UploadListener listener) {
if (mListeners != null && mListeners.contains(listener)) mListeners.remove(listener);
}
public static void upload() {
// ...
notifySuccess();
notifyFail();
}
private static void notifySuccess() {
if (mListeners == null) return;
for (UploadListener listener : mListeners) {
if (listener != null) listener.success();
}
}
private static void notifyFail() {
if (mListeners == null) return;
for (UploadListener listener : mListeners) {
if (listener != null) listener.fail();
}
}
}
interface UploadListener {
void success();
void fail();
}
void test() {
UploadFile.setListener(new UploadListener() {
@Override
public void success() {
// Observer 1
}
@Override
public void fail() {
}
});
UploadFile.setListener(new UploadListener() {
@Override
public void success() {
// Observer 2
}
@Override
public void fail() {
}
});
UploadFile.setListener(new UploadListener() {
@Override
public void success() {
// Observer 3
}
@Override
public void fail() {
}
});
UploadFile.setListener(new UploadListener() {
@Override
public void success() {
// Observer 4
}
@Override
public void fail() {
}
});
UploadFile.upload();
}
}