定义
结构
代码案例
定义抽象观察者接口
public interface Observer {
void update(String message);
}
定义微信用户类实现接口
@AllArgsConstructor
public class WeixinUser implements Observer{
private String username;
@Override
public void update(String message) {
System.out.println(this.username + "-" + message);
}
}
定义抽象主题类 包含3个规定的方法
public interface Subject {
//添加订阅者
public void attach(Observer observer);
//删除订阅者
public void detach(Observer observer);
//通知订阅者更新信息
public void notify(String message);
}
定义微信公众号类 实现该接口
public class SubscriptionSubject implements Subject{
//存储该公众号的用户
private List<Observer> weixinUserList = new ArrayList<>();
@Override
public void attach(Observer observer) {
weixinUserList.add(observer);
}
@Override
public void detach(Observer observer) {
weixinUserList.remove(observer);
}
@Override
public void notify(String message) {
for(Observer observer : weixinUserList){
observer.update(message);
}
}
}
测试使用
public class Client {
public static void main(String[] args) {
SubscriptionSubject subscriptionSubject = new SubscriptionSubject();
//创建微信用户
WeixinUser weixinUser = new WeixinUser("小A");
WeixinUser weixinUser2 = new WeixinUser("小B");
WeixinUser weixinUser3 = new WeixinUser("小C");
//订阅公众号
subscriptionSubject.attach(weixinUser);
subscriptionSubject.attach(weixinUser2);
subscriptionSubject.attach(weixinUser3);
//更新信息
subscriptionSubject.notify("新消息!!");
}
}