楔子
小七的朋友跟小七倾述,说他女朋友们希望他能像肚子里的蛔虫一样了解她的一举一动。小七微微一笑,这还不简单,弄个发布订阅(观察者)不就行了︿( ̄︶ ̄)︿!
被观察者
首先将小七朋友的女朋友抽象为一个类
public class Girlfriend {
private String name;
public Girlfriend(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
接下来让她们继承Observable
public class Girlfriend extends Observable {
private String name;
public Girlfriend(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void doSomething(Girlfriend girlfriend,String thing){
System.out.println(girlfriend.name + "在" + thing);
// 调用父类的方法,表明被观察者有变化
super.setChanged();
// 调用父类的方法,发送信息给观察者
super.notifyObservers(thing);
}
}
观察者
将小七的朋友抽象为另一个类
public class WinnerOfLife {
private String name;
public WinnerOfLife(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
给他赋予观察者的超能力
public class WinnerOfLife implements Observer {
private String name;
public WinnerOfLife(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
Girlfriend girlfriend = (Girlfriend) o;
System.out.println(this.name+"收到通知:"+girlfriend.getName()+"在"+arg);
}
}
测试类
public class Test {
public static void main(String[] args) {
// 给小七朋友new女朋友
Girlfriend girlfriend = new Girlfriend("小丽");
Girlfriend girlfriend2 = new Girlfriend("小芳");
// 请出小七朋友
WinnerOfLife winner = new WinnerOfLife("渣男");
// 将他们绑定在一起
girlfriend.addObserver(winner);
girlfriend2.addObserver(winner);
// 女朋友们开始活动了
girlfriend.doSomething(girlfriend,"逛街");
girlfriend2.doSomething(girlfriend2,"吃饭");
}
}
结果:
UML
注意:JDK实现观察者模式将在1.9过期
@Deprecated(since="9")