1. 程式人生 > >java常用設計模式--觀察者模式簡單例子

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();
}
}