本文来看下java设计模式之观察者模式。

观察者模式,顾名思义,一个被观察的人状态改变了,观察他的人也都知道了。不难理解。咱们举一个比较好的例子吧。以前一直说游戏什么的,咱们这次来看下文章。 现在的博客都是可以订阅的,而且我们使用了使用了一些工具后,他们更新了是可以随时通知到我们的。为了方便描述,我就直接说是博客更新了就通知到我们吧。 你看,我们的RSS订阅源

1
2
3
4
5
6
7
public interface RSS {

    public void addDevice(Device device);
    public void delDevice(Device device);
    public void notifyDevice(String message);

}

我们的博客

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Blog implements RSS {

    private List<Device> deviceList=new ArrayList<>();

    public Blog() {
    }

    @Override
    public void addDevice(Device device) {
        this.deviceList.add(device);
    }

    @Override
    public void delDevice(Device device) {
        this.deviceList.remove(device);
    }

    @Override
    public void notifyDevice(String message) {
        for (Device device:deviceList){
            device.update(message);
        }
    }


    public void updateArticle(){
        System.out.println("I write a new article");
        this.notifyDevice("new article");
    }

}

看看我们谁在观察这些博客文章吧。都有各种设备

1
2
3
public interface Device {
    public void update(String message);
}

我有个kindle,订阅了这些信息

1
2
3
4
5
6
7
public class Kindle implements Device {
    @Override
    public void update(String message) {
        System.out.println("the blog update");
        System.out.println("content is: "+message);
    }
}

好啦,我们来看下

1
2
3
4
5
6
7
8
public class Web {
    public static void main(String[] args) {
        Blog blog=new Blog();
        Device kindle=new Kindle();
        blog.addDevice(kindle);
        blog.updateArticle();
    }
}

不复杂吧! 你看,在我们这个订阅管理里面,我们有自己的RSS订阅源就相当于被观察者,然后我们的设备就相当于观察者,被观察者如果有了新的内容,就通知到观察者。很简单的一个流程。 而且,更好的消息是,java帮我们把RSS还有Device做好了。我们就直接继承就好啦。

1
2
3
4
5
6
7
public class OBlog extends Observable {
    public void updateArticle(){
        System.out.println("I write a new article");
        this.setChanged();
        this.notifyObservers("new article");
    }
}

我们就只需要写自己的业务就好啦。除此之外呢,注意我们在使用notifyObservers()之前要setChanged()来通知有内容更新。

1
2
3
4
5
6
7
public class OKindle implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("the blog update");
        System.out.println("content is: "+arg.toString());
    }
}

调用过程也很简单

1
2
3
4
        OKindle oKindle=new OKindle();
        OBlog oBlog=new OBlog();
        oBlog.addObserver(oKindle);
        oBlog.updateArticle();

..................分割线................. 似乎没有太复杂的,就没有什么需要解释的了.