public class SubscriptionSubject implements Subject{ private List<Observer> weixinUserlist = new ArrayList<Observer>(); @Override public void attach(Observer observer) { // TODO Auto-generated method stub weixinUserlist.add(observer); }
@Override public void deatch(Observer observer) { // TODO Auto-generated method stub weixinUserlist.remove(observer); }
@Override public void notify(String message) { // TODO Auto-generated method stub for (Observer observer : weixinUserlist) { observer.update(message); } }
}
客户端调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class Client { public static void main(String[] args) { SubscriptionSubject subscriptionSubject = new SubscriptionSubject(); //创建微信用户 WeixinUser user1 = new WeixinUser("小明"); WeixinUser user2 = new WeixinUser("小红"); WeixinUser user3 = new WeixinUser("小兰"); //订阅公众号 subscriptionSubject.attach(user1); subscriptionSubject.attach(user2); subscriptionSubject.attach(user3); subscriptionSubject.notify("程序猿公众号专栏更新了"); } }