定义消息发布者接口
package com.huhu.observer2;
public interface Observerable {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObserver();
}
定义观察者接口
package com.huhu.observer2;
public interface Observer {
public void update(String message);
}
实现发布者接口
package com.huhu.observer2;
import java.util.ArrayList;
import java.util.List;
public class WechatServer implements Observerable {
private List<Observer> list;
private String message;
public WechatServer(){
list = new ArrayList<>();
}
public void registerObserver(Observer o){
list.add(o);
}
public void removeObserver(Observer o){
if (!list.isEmpty()){
list.remove(o);
}
}
public void notifyObserver(){
for (Observer o: list){
o.update(message);
}
}
public void setInformation(String s){
message = s;
System.out.println("微信公众号更新消息啦");
notifyObserver();
}
}
实现观察者接口
package com.huhu.observer2;
public class User implements Observer{
private String message;
private String name;
public User(String name) {
this.name = name;
}
public void update(String message){
this.message = message;
read();
}
public void read(){
System.out.println(name + "收到微信消息:" + message);
}
}