观察者模式

<a href = "http://blog.csdn.net/u011240877/article/details/52683558">原文作者张拭心博客链接</a>

1. 首先定义 斧头帮老大 AxeGangBoss:

// 斧头帮老大,消息发送者,继承Observable
public class AxeGangBoss extends Observable {
    private String strName;
    public AxeGangBoss(String strName){
        this.strName = strName;
    }
    public String getStrName() {
        return strName;
    }
    public void setStrName(String strName) {
        this.strName = strName;
    }
    public void sendMsg (String strMsg){// 给小弟发送消息
        setChanged();
        notifyObservers(strMsg);
    }
}

2.定义 斧头帮小弟 AxeGangPeople:

// 斧头帮小弟,实现Observer接口
public class AxeGangPeople implements Observer {
    private String strName;

    public AxeGangPeople(String strName) {
        this.strName = strName;
    }
    public String getStrName() {
        return strName;
    }
    public void setStrName(String strName) {
        this.strName = strName;
    }
    @Override
    public void update(Observable observable, Object data) {
        AxeGangBoss writer;
        if(observable instanceof AxeGangBoss){
            writer = (AxeGangBoss) observable;
            Log.i("cctag", getStrName()+"收到来自:"+writer.getStrName()+",的消息:"+data.toString());
        }
    }
}

3.然后小弟去老大那登记,老大想做事就射穿云箭:

// 创建老大的实例对象
        AxeGangBoss boss = new AxeGangBoss("带头大哥");
// 创建小弟的实例对象
        AxeGangPeople p1 = new AxeGangPeople("路人甲");
        AxeGangPeople p2 = new AxeGangPeople("路人乙");
        AxeGangPeople p3 = new AxeGangPeople("路人丙");
// 老大将小弟收入麾下
        boss.addObserver(p1);
        boss.addObserver(p2);
        boss.addObserver(p3);
// 老大射出穿云箭
        boss.sendMsg("黄河大道东,速度来砍人。");

4.运行结果

Paste_Image.png

推荐阅读更多精彩内容