public class School extends Observable{
String SCname;
public School(String SCname) {
// TODO Auto-generated constructor stub
this.SCname = SCname;
}
public void SCpublish(String msg){
System.out.println(SCname + " 发布通知: " + msg);
setChanged(); //父类方法, 标记变化;
notifyObservers(); //父类方法, 发送通知
}
}
学生
public class Student implements Observer{
String STname;
public Student(String STname) {
// TODO Auto-generated constructor stub
this.STname = STname;
}
@Override
public void update(Observable o, Object arg) { //收到发布信息时,触发;
// TODO Auto-generated method stub
School sc = (School) o;
String msg = (String) arg;
System.out.println(STname + " 收到 "+ sc.SCname +" 通知,内容是 " + msg);
}
}
test
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
School sc = new School("北大青鸟");
Student s1 = new Student("韩梅");
Student s2 = new Student("李雷");
//添加订阅者
sc.addObserver(s1);
sc.addObserver(s2);
sc.SCpublish("Hello world!");
}
}
public class GuavaListener {
@Subscribe
public void guavaListener(String msg){
System.out.println("收到guava通知: " + msg);
}
}
发布者
public class Test {
public static void main(String[] args) {
EventBus eb = new EventBus();
GuavaListener gl = new GuavaListener();
eb.register(gl); //注册观察者;
eb.post("Hello world!"); //发布者发布消息;
}
}