public interface Observer {
void accept(String message);
}
public class ConcreteObserver implements Observer {
String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void accept(String message) {
System.out.println("观察者:" + name + "接收消息:" + message);
}
}
public interface BeiObserver {
void add(Observer observer);
void del(Observer observer);
void send(String message);
}
public class ConcreteBeiObserver implements BeiObserver {
ArrayList<Observer> list = new ArrayList<>();
public ConcreteBeiObserver() {
}
public ConcreteBeiObserver(ArrayList<Observer> list) {
this.list = list;
}
@Override
public void add(Observer observer) {
list.add(observer);
}
@Override
public void del(Observer observer) {
list.remove(observer);
}
@Override
public void send(String message) {
for (Observer observer : list) {
observer.accept(message);
}
}
}
测试
public class Test {
public static void main(String[] args) {
ConcreteObserver observer1 = new ConcreteObserver("周杰伦");
ConcreteObserver observer2 = new ConcreteObserver("周杰");
ConcreteBeiObserver concreteBeiObserver = new ConcreteBeiObserver();
concreteBeiObserver.add(observer1);
concreteBeiObserver.add(observer2);
concreteBeiObserver.send("更新");
}
}
网友评论