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