java常用设计模式--观察者模式简单例子

package com.ruanyun;

import java.util.List;
import java.util.Vector;

/**
* @Auther: maxw
* @Date: 2018/11/10 16:14
* @Description:观察者模式
* 基本概念:
* 观察者模式属于行为型模式,其意图是定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
* 这一个模式的关键对象是目标(Subject)和观察者(Observer)。一个目标可以有任意数目的依赖它的观察者,一旦目标的状态发生改变,所有的观察者都得到通知,
* 作为对这个通知的响应,每个观察者都将查询目标以使其状态与目标的状态同步。
* 适用场景:
* 观察者模式,用于存在一对多依赖关系的对象间,当被依赖者变化时,通知依赖者全部进行更新。
* 因此,被依赖者,应该有添加/删除依赖者的方法,且可以将添加的依赖者放到一个容器中;且有一个方法去通知依赖者进行更新。
*/
public class Test2 {
public static void main(String args[]){
Vector<Student> students =new Vector<Student>();
Teacher teacher =new Teacher();
for(int i=0;i<5;i++){
Student student =new Student(teacher,"student"+i);
students.add(student);
teacher.addStudent(student);
}
for(Student student :students){
student.showTelphone();
}
teacher.setTelphone("100000");
for(Student student :students){
student.showTelphone();
}
teacher.setTelphone("111111");
for(Student student :students){
student.showTelphone();
}
}
}
class Teacher{
private String telphone;
private Vector<Student> students;

public Teacher() {
telphone = "";
students = new Vector();
}
//添加学生
public void addStudent(Student student){
students.add(student);
}
//移除学生
public void removeStudent(Student student){
students.remove(student);
}

public String getTelphone() {
return telphone;
}
//更新手机号码
public void setTelphone(String telphone) {
this.telphone = telphone;
notice(); //设置手机号码的时候通知学生 关键
}

private void notice(){
for(Student student : students){
student.updateTelphone();
}
}
}
class Student{
private String teachPhone;
private Teacher teacher;
private String name;

public Student(Teacher teacher, String name) {
this.teacher = teacher;
this.name = name;
}
public void showTelphone(){
System.out.println(name+"老师电话为:"+teachPhone);
}
public void updateTelphone(){
teachPhone = teacher.getTelphone();
}
}

猜你喜欢

转载自www.cnblogs.com/maxiw/p/9939905.html