设计模式之观察者模式

Observer(观察者)模式从名称也可以看出该设计模式的使用意义。当用户想让某一事物或者行为在改变时能够主动修改其他某些事物或者行为时,就需要观察者模式。观察者模式分为两种对象:观察对象和依赖观察者,当观察对象改变时,其依赖观察者也会做相应的改变。观察者设计模式应用在许多地方,比如Android中实现有信息插入数据库的时候动态修改短信列表,就需要短信软件观察Android短信数据库,达到实时同步。

由于java内部实现了观察者模式,我们只需要在其基础上进行业务逻辑处理即可。

举个警察监控小偷的例子,如果小偷有动静,警察也会做相应的动静。小偷睡觉,警察就睡觉;小偷走路,警察就会跟随;小偷偷东西,警察就把他抓了。

小偷实现:

public class Thief extends Observable{

    public void sleep() {

       System.out.println("thief issleeping now");

       setChanged();

       notifyObservers("sleep");

    }

    public void walk() {

       System.out.println("thief iswalking now");

       setChanged();

       notifyObservers("walk");

    }

    public void steal() {

       System.out.println("good nightfor stealing");

       setChanged();

       notifyObservers("steal");

    }

}

 警察实现:

public class Police implements Observer {

    private static int count = 0;

    private int index = ++count;

    @Override

    public void update(Observable thief, Object actor) {

       if(actor.equals("sleep")) {

           System.out.println("police" + index + " issleeping");

       } else if(actor.equals("walk")) {

           System.out.println("police" + index + " istracking");

       } else if(actor.equals("steal")) {

           System.out.println("police" + index + " catch thethief");

       }

    }

 }

 

测试代码:

public static void main(String[] args) {

       Thief thief = new Thief();

       Police p1 = new Police();

       Police p2 = new Police();

       thief.addObserver(p1);

       thief.addObserver(p2);

       thief.sleep();

       thief.walk();

       thief.steal();

    }

打印结果如下:

thief is sleeping now

police 2 is sleeping

police 1 is sleeping

thief is walking now

police 2 is tracking

police 1 is tracking

good night for stealing

police 2 catch the thief

police 1 catch the thief


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值