Observer Pattern
2024-06-12 本文已影响0人
杨志聪
解决的问题
一个Excel表格,你修改一个地方的数值(DataSource),相关的图表(Chart)和另一个表格(SpreadSheet)也会同步发生变化。
代码
Observer
:
package com.cong.designpattern.observer;
public interface Observer {
public void update(int newValue);
}
DataSource
:
package com.cong.designpattern.observer;
import java.util.ArrayList;
import java.util.List;
public class DataSource {
private int value;
private List<Observer> observers;
public DataSource() {
this.value = 0;
this.observers = new ArrayList<>();
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
this.notifyObservers(value);
}
public void addObserver(Observer observer) {
this.observers.add(observer);
}
public void removeObserver(Observer observer) {
this.observers.remove(observer);
}
private void notifyObservers(int value) {
for (Observer observer : this.observers) {
observer.update(value);
}
}
}
Chart
:
package com.cong.designpattern.observer;
public class Chart implements Observer {
@Override
public void update(int newValue) {
System.out.println("Chart did updated with " + newValue);
}
}
SpreadSheet
:
package com.cong.designpattern.observer;
public class SpreadSheet implements Observer {
@Override
public void update(int newValue) {
System.out.println("Spread sheet did updated with " + newValue);
}
}
Test code:
DataSource dataSource = new DataSource();
SpreadSheet spreadSheet = new SpreadSheet();
Chart chart = new Chart();
dataSource.addObserver(spreadSheet);
dataSource.addObserver(chart);
dataSource.setValue(1);