ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 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是世界上最好用的语言!"); } }