public class Subject {
private List<Observer> observers;
public Subject() {
observers = new ArrayList<>();
}
protected void attach(Observer observer) {
observers.add(observer);
}
protected void detach(Observer observer) {
observers.remove(observer);
}
protected void notify_(Object args) {
observers.forEach(observer -> observer.update(args));
}
}
public class VolumeSubject extends Subject {
private Integer vol;
public void changeVol(Integer vol){
this.vol=vol;
notify_(vol);
}
}
public interface Observer {
void update(Object message);
}
public class SpeakerObserver implements Observer {
public SpeakerObserver(Subject subject){
subject.attach(this);
}
@Override
public void update(Object vol) {
System.out.println("扬声器音量调整"+vol);
}
}
public class VolumeBarObserver implements Observer {
public VolumeBarObserver(Subject subject){
subject.attach(this);
}
@Override
public void update(Object vol) {
System.out.println("音量条显示器调整"+vol);
}
}
public class App {
public static void main(String[] args) {
VolumeSubject subject=new VolumeSubject();
Observer speaker=new SpeakerObserver(subject);
Observer volumeBar=new VolumeBarObserver(subject);
subject.changeVol(4);
subject.changeVol(5);
subject.changeVol(6);
}
}