观察者模式(又被称为发布-订阅(Publish/Subscribe)模式,属于行为型模式的一种,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己。
subject主题类:
public class Subject {
List<Observe> list;
public Subject() {
this.list = new ArrayList<Observe>();
}
public void notice() {
System.out.println("老板来了大家开始工作!");
for (int i = 0; i < list.size(); i++) {
list.get(i).work();
}
}
public void attach(Observe obs) {
list.add(obs);
}
public void detach(Observe obs) {
for (int i = 0; i < list.size(); i++) {
Observe tem = list.get(i);
if (tem.getName().equals(obs.getName())) {
list.remove(i);
return;
}
}
}
}
观察者
public class Observe {
private String name;
public Observe(String name){
this.name=name;
}
public String getName(){
return name;
}
public void work(){
System.out.println(name+" 收到了,开始工作!");
}
}
测试代码:
public class T {
public static void main(String[] args) {
Subject subject = new Subject();
Observe ob1 = new Observe("ob1");
Observe ob2 = new Observe("ob2");
subject.attach(ob1);
subject.attach(ob2);
subject.notice();
}
}