## 1. 什么是观察者设计模式
## 2. 怎么理解观察者设计模式
## 3. 代码怎么实现
public interface Observer {
public void update(String message);
}
public interface Observerable {
public void registerObservice(Observer o);
public void removeObserver(Observer o);
public void notifyObserver();
}
public class WacherServer implements Observerable{
private List<Observer> list;
private String message;
public WacherServer() {
list = new ArrayList<Observer>();
}
@Override
public void registerObservice(Observer o) {
list.add(o);
}
@Override
public void removeObserver(Observer o) {
if(!list.isEmpty())
list.remove(o);
}
@Override
public void notifyObserver() {
for(int i = 0; i < list.size(); i++) {
Observer oserver = list.get(i);
oserver.update(message);
}
}
public void setInfomation(String s) {
this.message = s;
System.out.println("微信服务更新消息: " + s);
//消息更新,通知所有观察者
notifyObserver();
}
}
public class User implements Observer{
private String name;
private String message;
public User(String name) {
this.name = name; }
@Override
public void update(String message) {
this.message = message;
read(); }
public void read() {
System.out.println(name + " 收到推送消息: " + message);}}
public class Test {
public static void main(String[] args) {
WacherServer server = new WacherServer();
Observer userZhang = new User("ZhangSan");
Observer userLi = new User("LiSi");
Observer userWang = new User("WangWu");
server.registerObservice(userZhang);
server.registerObservice(userLi);
server.registerObservice(userWang);
server.setInfomation("PHP是世界上最好用的语言!");
System.out.println("----------------------------------------------");
server.removeObserver(userZhang);
server.setInfomation("JAVA是世界上最好用的语言!");
}
}