观察者模式(发布-订阅 Publish/Subscribe)
最后发布时间:2024-11-27 14:55:02
浏览量:
参考
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
abstract class Subject{
private List<Observer> observers =new ArrayList<>();
public void attach(Observer observer){
observers.add(observer);
}
public void detach(Observer observer){
observers.remove(observer);
}
public void notice(){
observers.forEach(it->it.update());
}
}
abstract class Observer{
public abstract void update();
}
class ConcreteSubject extends Subject{
@Getter
@Setter
private String name;
}
class ConcreteObserver1 extends Observer{
private ConcreteSubject subject;
public ConcreteObserver1(ConcreteSubject subject){
this.subject = subject;
}
@Override
public void update() {
System.out.println("观察者ConcreteObserver1观察到,通知者"+subject.getName()+"的通知!");
}
}
class ConcreteObserver2 extends Observer{
private ConcreteSubject subject;
public ConcreteObserver2(ConcreteSubject subject){
this.subject = subject;
}
@Override
public void update() {
System.out.println("观察者ConcreteObserver2观察到,通知者"+subject.getName()+"的通知!");
}
}
public class test {
public static void main(String[] args) {
ConcreteSubject concreteSubject =new ConcreteSubject();
concreteSubject.setName("zs");
concreteSubject.attach(new ConcreteObserver1(concreteSubject));
concreteSubject.attach(new ConcreteObserver2(concreteSubject));
concreteSubject.notice();
}
}