美文网首页
观察者模式

观察者模式

作者: 隔壁老C | 来源:发表于2016-11-08 10:06 被阅读0次

    <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

    相关文章

      网友评论

          本文标题:观察者模式

          本文链接:https://www.haomeiwen.com/subject/empwyttx.html