在观察者模式中有如下角色:
抽象观察者
public interface Observer {
void update(String msg);
}
具体观察者
public class User implements Observer{
//用户名
private String name;
public User(String name) {
this.name = name;
}
@Override
public void update(String msg) {
System.out.println(name + msg);
}
}
抽象被观察者
public interface Subject {
//增加订阅者
void attach(Observer observer);
//删除订阅者
void detach(Observer observer);
//通知订阅者更新消息
void notify(String message);
}
具体被观察者
public class SpecificSubject implements Subject{
//定义一个用来存储已订阅的用户的集合
private List<Observer> list = new ArrayList<>();
@Override
public void attach(Observer observer) {
list.add(observer);
}
@Override
public void detach(Observer observer) {
list.remove(observer);
}
@Override
public void notify(String message) {
for (Observer observer : list){
observer.update(message);
}
}
}
测试类
public class Test {
public static void main(String[] args) {
SpecificSubject subject = new SpecificSubject();
//创建三个用户
User user1 = new User("zs");
User user2 = new User("ls");
User user3 = new User("ww");
//订阅
subject.attach(user1);
subject.attach(user2);
subject.attach(user3);
//更新
subject.notify("2022-08-07斗罗大陆更新了!");
System.out.println("============");
subject.detach(user2);
subject.notify("2022-08-08斗罗大陆更新了!");
}
}
输出结果
优点:
缺点: