项目地址
GitHub: https://github.com/AlionSSS/MyNotifier
你可能需要知道
- 单例设计模式
- 观察者设计模式
- 熟悉HashMap、HashSet、Interface
使用示例
- 按topic注册观察者
Notify.getNotifier().subscribe("Chinese", new EventObserver() {
@Override
public void onEvent(Object info) {
System.out.println("info = " + info);
}
});
- 按topic分发消息
Notify.getNotifier().post("Chinese", "hello");
源代码
注:源码请见GitHub
- Event 发生接口
- MyNotifier 订阅/分发的功能接口
- Notify消息订阅/分发的具体实现类
测试一下
public class Main {
public static void main(String[] args) {
MyNotifier notifier = Notify.getNotifier();
notifier.subscribe("China", new EventObserver() {
@Override
public void onEvent(Object info) {
System.out.println("info = " + info);
}
});
notifier.subscribe("China", new EventObserver() {
@Override
public void onEvent(Object info) {
System.out.println("info = " + info);
}
});
notifier.subscribe("American", new EventObserver() {
@Override
public void onEvent(Object info) {
System.out.println("info = " + info);
}
});
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
MyNotifier notifier = Notify.getNotifier();
notifier.post("China", "你好1");
Thread.sleep(3000);
notifier.post("American", "hello");
Thread.sleep(10000);
notifier.post("China", "你好2");
notifier.post("American", "hello2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
for (int i = 0; i < 99; i++) {
try {
Thread.sleep(500);
System.out.println("MainThread ---> " + i);
if (i == 20) {
System.out.println("注销掉China");
Notify.getNotifier().unSubscribe("China");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}