应用场景:
当一个对象的改变需要同时改变其他对象的时候
/**
* 被观察者的对象
* @author ZhangSheng
*
*/
public class Person_Observable extends Observable {
private String name,sex;
private int age;
public Person_Observable(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public Person_Observable() {
super();
}
@Override
public String toString() {
return "Person_Observable [name=" + name + ", age=" + age + ", sex="
+ sex + "]";
}
public String getName() {
return name;
}
/**
* 当被观众对象数据发送改变时
* 通知观察者
* @param name
*/
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers();
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
setChanged();
notifyObservers();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
setChanged();
notifyObservers();
}
}
----------------------------------------------------------------------
/**
* 一个观察者对象
* @author ZhangSheng
*
*/
public class MyObserver implements Observer {
//某一个具体的观察者对象
private int i;
//被观察的对象,这里可以列举多个
private Person_Observable person_Observable;
public MyObserver(int observer){
this.i = observer;
System.out.println("我是观察者"+i);
}
//当被观察的对象数据发生改变时 ;
//观察者对象会自动回调
@Override
public void update(Observable observable, Object object) {
person_Observable = (Person_Observable) observable;
System.out.println("观察者"+i+"发现被观察者的数据发送改变了--》"+person_Observable);
}
}
-----------------------------------------------------------------------
/**
* 观察者模式简单实例
* @author ZhangSheng
*
*/
public class MainActivity extends Activity {
private Person_Observable observable;
private int year;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化被观察者对象
//改变被观察者的年龄
year = 10;
observable = new Person_Observable("张三", year, "男");
//初始化观察者对象
MyObserver observer1 = new MyObserver(1);
MyObserver observer2 = new MyObserver(2);
MyObserver observer3 = new MyObserver(3);
MyObserver observer4 = new MyObserver(4);
MyObserver observer5 = new MyObserver(5);
//为被观察者对象添加观察者
observable.addObserver(observer1);
observable.addObserver(observer2);
observable.addObserver(observer3);
observable.addObserver(observer4);
observable.addObserver(observer5);
}
//点击按钮,改变被观察者的年龄。查看结果
/**
* 可以得知 :观察者模式:
* 就是当被观察者的对象数据发生改变时,它所拥有的观察者对象都会同时得到通知
* @param v
*/
public void increase(View v){
observable.setAge(++year);
}
}