观察者模式:
意图:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
当一个对象放生改变,所有的依赖对象都将得到通知时使用。
关键代码:在抽象类里有一个 ArrayList 存放观察者们。
import java.util.Observable;
import java.util.Observer;
public class Demo {
public static void main(String[] args) {
wolf w = new wolf(“wolf1”);
sheep s1 = new sheep(“s1”);
sheep s2 = new sheep(“s2”);
sheep s3 = new sheep(“s3”);
w.addObserver(s1);
w.addObserver(s2);
String state = “hungry”;
w.shout(state);
}
}
class wolf extends Observable{
private String name;
public wolf(String name) {
this.name = name;
}
public void shout(String state) {
System.out.println(name+“shouting”);
this.hasChanged();
this.notifyObservers(state);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class sheep implements Observer{
private String name;
private String state = “eating”;
public sheep(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
wolf w = (wolf)o;
System.out.println(w.getName()+"shouting and "+arg+" "+this.name+"running....");
setState("running");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}