//Subject
package com
/**
* @author youngmaster
* @E
* @create time
*/
/**
* 察者模式屬於行為型模式
* 當一個對象的狀態發生改變時
* 在制作系統的過程中
* 需要維護相關對象間的一致性
* 因為這樣降低了他們的可充用性
* 一個目標可以有任意數目的依賴它的觀察者
* 作為對這個通知的響應
* 目標是通知的發布者
*/
/**
* subject
*目標接口
*/
public interface Subject {
public void addObserver(Observer o);
public void deletObserver(Observer o);
public void notice();
}
//Observer
package com
/**
* @author youngmaster
* @E
* @create time
*/
/**
*觀察者接口
*/
public interface Observer {
public void update();
}
//Teacher
package com
import java
/**
* @author youngmaster
* @E
* @create time
*/
/**
*目標接口實現
*/
public class Teacher implements Subject {
private String phone;
@SuppressWarnings(
private Vector students;
@SuppressWarnings(
public Teacher() {
phone =
students = new Vector();
}
@SuppressWarnings(
@Override
public void addObserver(Observer o) {
students
}
@Override
public void deletObserver(Observer o) {
students
}
@Override
public void notice() {
for (int i =
}
}
public void setPhone(String phone) {
this
notice();
}
public String getPhone() {
return phone;
}
}
//Student
package com
/**
* @author youngmaster
* @E
* @create time
*/
/**
*觀察者接口實現
*/
public class Student implements Observer {
private String name;
private String phone;
private Teacher teacher;
public Student(String name
}
public void show() {
System
}
@Override
public void update() {
phone = teacher
}
}
//Client
package com
import java
/**
* @author youngmaster
* @E
* @create time
*/
/**
*測試類
*/
public class Client {
/**
* @param args
*/
@SuppressWarnings(
public static void main(String[] args) {
Vector students = new Vector();
Teacher teacher = new Teacher();
for (int i =
Student student = new Student(
}
teacher
for (int i =
((Student) students
System
teacher
for (int i =
((Student) students
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27566.html