//通知者
public class Boy {
//状态
private String state;
//观察者列表
public List<Girl> girls = new ArrayList<Girl>();
//通知
public void notifyGirls(){
for(Girl g : girls ){
g.update();
}
}
//增加
public void attach(Girl g){
girls.add(g);
}
//减少
public void detach(Girl g){
girls.remove(g);
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public static void main(String[] args){
Boy ysen = new Boy();
Girl girlFriend = new Girl();
girlFriend.setName("hyy");
//下面两句 ,两个具体对象相互耦合了,违背了依赖倒转原则,应该让程序都依赖抽象,这里需要解耦
//需要给Boy 和 Girl 各 添加一个基类,让它们依赖抽象
girlFriend.setBoy(ysen);
ysen.attach(girlFriend);
ysen.setState("我回来了哦~~");
ysen.notifyGirls();
}
}
//观察者
public class Girl {
private String name;
private Boy boy;
public void update(){
System.out.println(boy.getState()+name+"起床做饭咯");
}
public Boy getBoy() {
return boy;
}
public void setBoy(Boy boy) {
this.boy = boy;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}