java中的观察者/订阅者模式实践 – Observable、Observer

这方面的资料搜索一下很多,但是自己一直没有实践过。今天用到了,做下记录。名词解释:

观察者,Observer
被观察者,Observable

举例,过年放烟花,烟花放在中间一直燃烧,就是被观察者;
而大家在周围看,就是观察者(哇~~~猴赛雷)
直接上代码:

测试一下:

输出:

I am fired, check on that
XiaoLi watched: qiu…qiu…qiu…
XiaoHong watched: qiu…qiu…qiu…
XiaoQiang watched: qiu…qiu…qiu…
XiaoMing watched: qiu…qiu…qiu…

之前使用的是直接new一个Observable对象,导致无法调用父类的setChanged方法。

见->java 订阅者模式不执行update

 

4 thoughts on “java中的观察者/订阅者模式实践 – Observable、Observer

  1. Hello there! Quick question that’s entirely off topic. Do you
    know how to make your site mobile friendly? My
    blog looks weird when browsing from my apple iphone.
    I’m trying to find a theme or plugin that might be able to correct this issue.
    If you have any suggestions, please share. Thanks!

    1. Thks for your commit.
      I see you’re using the “Penscrach” theme, and that is also a responstive theme, I test your website on my Chrome browser use Device mode, it looks good, not wired.
      My website is using “Tribute” theme, If you like, you can try it.

  2. I’ll immediately take hold of your rss feed as I can not in finding your email subscription hyperlink or newsletter service.
    Do you’ve any? Please let me realize so that I may just
    subscribe. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

注意: 评论者允许使用'@user空格'的方式将自己的评论通知另外评论者。例如, ABC是本文的评论者之一,则使用'@ABC '(不包括单引号)将会自动将您的评论发送给ABC。使用'@all ',将会将评论发送给之前所有其它评论者。请务必注意user必须和评论者名相匹配(大小写一致)。