观察者模式
核心:在抽象类里有一个 ArrayList 存放观察者们
代码不算完整,那个table的展示省略
package com.cai.observer;
import java.util.ArrayList;
import java.util.List;
/**
* @Description
* @Author Cai
* @Create 2021-06-12-15:34
*/
interface Table {
void show();
void notifyData(DataA data);
}
class Table1 implements Table{
@Override
public void show() {
SpreadsheetView.print1();
}
@Override
public void notifyData(DataA data) {
data.add(this);
}
}
class Table2 implements Table{
@Override
public void show() {
SpreadsheetView.print2();
}
@Override
public void notifyData(DataA data) {
data.add(this);
}
}
abstract class DataA{
protected List<Table> list = new ArrayList<>();
public void add(Table table){
list.add(table);
}
public void remove(Table table){
list.remove(table);
}
public abstract void notifyObserver();
}
class SourceData extends DataA{
@Override
public void notifyObserver() {
for (Table table : list) {
table.show();
}
}
}
class SpreadsheetView{
static void print1(){
System.out.println("打印图表1");
}
static void print2(){
System.out.println("打印图表2");
}
}
public class Main{
public static void main(String[] args) {
DataA dataa = new SourceData();
Table table1 = new Table1();
Table table2 = new Table2();
table1.notifyData(dataa);
table2.notifyData(dataa);
dataa.notifyObserver();
}
}