/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package observer;
import java.util.ArrayList;
/**
* 觀察者
* @author lvxda
*/
public class Cat implements Subject{
private String name;//貓的稱呼
private ArrayList<Observer> observers = new ArrayList<Observer>(); //被觀察者註冊到名單中
public Cat(String name){
this.name = name;
}
public void aim(Observer obs) {
this.observers.add(obs);
}
//當觀察者事件觸發時,要通知被觀察者,被觀察者作出必要的反應
public void cry(){
System.out.println(name + " 大吼一聲: 那裏跑?");
for(Observer obs : observers){
obs.response();
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package observer;
/**
* 被觀察者
* @author lvxda
*/
public class Master implements Observer {
private Subject subject;
public Master(Subject sub){
this.subject = sub;
subject.aim(this);
}
Master(String string) {
throw new UnsupportedOperationException("Not yet implemented");
}
public void response() {
System.out.println("女主人驚醒.....");
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package observer;
import com.sun.org.apache.xpath.internal.axes.SubContextList;
/**
* 被觀察者
* @author lvxda
*/
public class Mouse implements Observer{
private String name;//名稱
private Subject subject;
public Mouse(String name, Subject subject){
this.name = name;
this.subject = subject;
subject.aim(this);
}
public void response() {
System.out.println(name + " 撒丫子就跑......");
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package observer;
/**
*
* @author lvxda
*/
public interface Observer {
void response();
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package observer;
/**
*
* @author lvxda
*/
public interface Subject {
void aim(Observer obs);
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package observer;
/**
*
* @author lvxda
*/
public class Test {
public static void main(String[] args){
//創建貓對象,花花
Cat cat = new Cat("花花");
//創建女主人對象
Master master = new Master(cat);
//創建兩個老鼠對象
Mouse m1 = new Mouse("大白",cat);
Mouse m2 = new Mouse("小白", cat);
//當花花發現大白和小白時候,他大吼一聲
cat.cry();
}
}