package com.jmj.pattern.observer;/*抽象观察者类*/
public interface Observer {void update(String message);}
package com.jmj.pattern.observer;/*** 抽象主题角色*/
public interface Subject {//添加观察者对象void attach(Observer observer);//删除订阅者void detach(Observer observer);//通知订阅者更新消息void notify(String message);}
package com.jmj.pattern.observer;import java.util.ArrayList;
import java.util.List;public class SubscriptionSubject implements Subject{//定义一个集合,用来存储多个观察者对象private List<Observer> weiXinUserList=new ArrayList<>();@Overridepublic void attach(Observer observer) {weiXinUserList.add(observer);}@Overridepublic void detach(Observer observer) {weiXinUserList.remove(observer);}@Overridepublic void notify(String message) {for (Observer observer : weiXinUserList) {observer.update(message);}}
}
package com.jmj.pattern.observer;public class WeiXinUser implements Observer{private String name;public WeiXinUser(String name) {this.name = name;}@Overridepublic void update(String message) {System.out.println(name+"-"+message);}
}
package com.jmj.pattern.observer;public class Client {public static void main(String[] args) {//1.创建公众号对象SubscriptionSubject subject =new SubscriptionSubject();//2.订阅公众号subject.attach(new WeiXinUser("孙悟空"));subject.attach(new WeiXinUser("猪悟能"));subject.attach(new WeiXinUser("沙悟净"));//3.公众号更新,发出新消息给订阅者subject.notify("公众号更新了");;}}