观察者模式
abstract class Subject{
protected ArrayList<Observer> list = new ArrayList<>();
void notift();
void addObserver(Observer observer);
void removeObserver(Observer observer);
}
抽象观察对象
class ConcreteSubject extends Subject{
public void notify(){
for(int i = 0;i < list.size();i++){
list.get(i).update("坐骑:秋名山神车---五菱宏光");
}
}
public addObserver(Observer observer){
list.add(observer);
}
public removeObserver(Observer observer){
list.remove(observer);
}
}
具体观察对象
interface Observer{
void update(String str);
}
抽象观察者
class ConcreteObserver implements Observer{
public void update(String str){
System.out.println(str);
}
}
观察者
class Client{
public static void main(String[] args){
Subject mSubject = new ConcreteSubject();
mSubject.add(new ConcreteObserver());
mSubject.add(new ConcreteObserver());
mSubject.add(new ConcreteObserver());
mSubject.notify();
}
}
客户端