//Subjectjava
package comyoungmastermodelObserver;
/**
* @author youngmaster
* @Email:young * @version myEclipse
* @create time上午::
*/
/**
* 察者模式属于行为型模式其意图是定义对象间的一种一对多的依赖关系
* 当一个对象的状态发生改变时所有依赖于它的对象都得到通知并被自动更新
* 在制作系统的过程中将一个系统分割成一系列相互协作的类有一个常见的副作用
* 需要维护相关对象间的一致性我们不希望为了维持一致性而使各类紧密耦合
* 因为这样降低了他们的可充用性这一个模式的关键对象是目标(Subject)和观察者(Observer)
* 一个目标可以有任意数目的依赖它的观察者一旦目标的状态发生改变所有的观察者都得到通知
* 作为对这个通知的响应每个观察者都将查询目标以使其状态与目标的状态同步这种交互也称为发布订阅模式
* 目标是通知的发布者他发出通知时并不需要知道谁是他的观察者可以有任意数据的观察者订阅并接收通知
*/
/**
* subject
*目标接口
*/
public interface Subject {
public void addObserver(Observer o);
public void deletObserver(Observer o);
public void notice();
}
//Observerjava
package comyoungmastermodelObserver;
/**
* @author youngmaster
* @Email:young * @version myEclipse
* @create time上午::
*/
/**
*观察者接口
*/
public interface Observer {
public void update();
}
//Teacherjava
package comyoungmastermodelObserver;
import javautilVector;
/**
* @author youngmaster
* @Email:young * @version myEclipse
* @create time上午::
*/
/**
*目标接口实现
*/
public class Teacher implements Subject {
private String phone;
@SuppressWarnings(unchecked)
private Vector students;
@SuppressWarnings(unchecked)
public Teacher() {
phone = ;
students = new Vector();
}
@SuppressWarnings(unchecked)
@Override
public void addObserver(Observer o) {
studentsadd(o);
}
@Override
public void deletObserver(Observer o) {
studentsremove(o);
}
@Override
public void notice() {
for (int i = ; i < studentssize(); i++) { ((Observer) studentsget(i))update();
}
}
public void setPhone(String phone) {
thisphone = phone;
notice();
}
public String getPhone() {
return phone;
}
}
//Studentjava
package comyoungmastermodelObserver;
/**
* @author youngmaster
* @Email:young * @version myEclipse
* @create time上午::
*/
/**
*观察者接口实现
*/
public class Student implements Observer {
private String name;
private String phone;
private Teacher teacher;
public Student(String name Teacher teacher) { thisname = name; thisteacher = teacher;
}
public void show() {
Systemoutprintln(Name: + name + \nTeachers phone: + phone);
}
@Override
public void update() {
phone = teachergetPhone();
}
}
//Clientjava
package comyoungmastermodelObserver;
import javautilVector;
/**
* @author youngmaster
* @Email:young * @version myEclipse
* @create time上午::
*/
/**
*测试类
*/
public class Client {
/**
* @param args
*/
@SuppressWarnings(unchecked)
public static void main(String[] args) {
Vector students = new Vector();
Teacher teacher = new Teacher();
for (int i = ; i < ; i++) {
Student student = new Student(student + i teacher); studentsadd(student); teacheraddObserver(student);
}
teachersetPhone();
for (int i = ; i < ; i++)
((Student) studentsget(i))show();
Systemoutprintln(\n============================\n);
teachersetPhone();
for (int i = ; i < ; i++)
((Student) studentsget(i))show();
}
}