你的位置:首页 > Java教程

[Java教程]猫叫老鼠跑

  当一个对象的状态发生改变时,他的所有依赖者都会收到通知并自动更新---------观察者模式

  即,猫A发出了叫声,老鼠B(老鼠C,D,E,F...)听到了这个声音,立即掉头就跑.

 1 package ares.core; 2  3 import java.util.ArrayList; 4  5 public class Cat implements Subject { 6   private ArrayList<Observer> observers = new ArrayList<Observer>(); 7   private String name; 8  9   public Cat(String name) {10     this.name = name;11   }12   13   public String getName() {14     return this.name;15   }16 17   @Override18   public void register(Observer o) {19     observers.add(o);20   }21 22   @Override23   public void remove(Observer o) {24     if (observers != null && observers.size() > 0) {25       int index = observers.indexOf(o);26       if (index >= 0) {27         observers.remove(index);28       }29     }30   }31 32   @Override33   public void notifyObserver() {34     for (Observer observer : observers) {35       observer.listen();36     }37   }38 39   public void shout() {40     System.out.println(this.name+":喵~喵~");41     notifyObserver();42   }43 44 }

1 package ares.core;2 3 public interface Subject {4   public void register(Observer o);5 6   public void remove(Observer o);7 8   public void notifyObserver();9 }

 1 package ares.core; 2  3 public class Mouse implements Observer { 4   private Cat cat; 5   private String name; 6  7   Mouse(String name, Cat cat) { 8     this.name = name; 9     this.cat = cat;10     cat.register(this);11   }12 13   @Override14   public void listen() {15     System.out.println(this.name + "听见"+cat.getName()+"叫!");16     run();17   }18 19   public void run() {20     System.out.println(this.name + ":"+cat.getName()+"来了,兄弟们快跑");21   }22 23 }

1 package ares.core;2 3 public interface Observer {4   public void listen();5 }

package ares.core;public class Main {  public static void main(String[] args) {    Cat cat = new Cat("大洋芋");    Mouse mouse=new Mouse("小米渣", cat);    cat.shout();  }}