首页 > 代码库 > java 观察者模式

java 观察者模式

/** 抽象的观察者 */
public interface Watcher {
    // status 为 被被观察着传递过来的状态
    public void update(String status);
}
import java.util.LinkedList;

/** 抽象的被观察者 */
public abstract class Watched {
    /** 用来保存注册的观察者对象 */
    protected LinkedList<Watcher> watcherList = new LinkedList<Watcher>();

    /** 注册观察者对象 */
    public abstract void add(Watcher watcher);

    /** 删除观察者对象 */
    public abstract void remove(Watcher watcher);

    /** 通知所有注册的观察者对象 */
    public abstract void notifyWatchers();
}
// 具体的观察者
public class Boy implements Watcher {

    @Override
    public void update(String status) {
        System.out.println(this + " 监听到状态 " + status);
    }
}
/** 具体的被观察者: 添加和删除方法最好加上同步 */
public class Girl extends Watched {
    private String status;

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public synchronized void add(Watcher watcher) {
        watcherList.add(watcher);
    }

    @Override
    public synchronized void remove(Watcher watcher) {
        watcherList.remove(watcher);
    }

    @Override
    public void notifyWatchers() {
        for (Watcher w : watcherList) {
            w.update(status);
        }
    }
}

测试代码与结果

public class Test {
    public static void main(String[] args) throws Exception {
        Girl girl = new Girl();
        for (int i = 0; i < 3; i++) {
            girl.add(new Boy());
        }
        girl.setStatus("happy");
        girl.notifyWatchers();
        TimeUnit.SECONDS.sleep(1);
        girl.setStatus("unhappy");
        girl.notifyWatchers();
    }
}

技术分享

 

参考: 

http://www.cnblogs.com/mengdd/archive/2013/02/07/2908929.html

http://www.cnblogs.com/mengdd/archive/2013/02/07/2908929.html

java 观察者模式