博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 观察者模式
阅读量:6621 次
发布时间:2019-06-25

本文共 1804 字,大约阅读时间需要 6 分钟。

IWatched:

/** * @author com.tiantian * @version 创建时间:2012-11-20 下午4:58:25 */public interface IWatched {    public void addWatcher(IWatcher watcher);    public void removeWatcher(IWatcher watcher);    public void notifyWatchers(String msg);}

IWatcher:

/** * @author com.tiantian * @version 创建时间:2012-11-20 下午4:55:23 */public interface IWatcher {    public void update(String msg);}

Watched:

/** * @author com.tiantian * @version 创建时间:2012-11-20 下午5:01:05 */public class Watched implements IWatched{    private List
watchers = new ArrayList
(); @Override public void addWatcher(IWatcher watcher) { watchers.add(watcher); } @Override public void removeWatcher(IWatcher watcher) { watchers.remove(watcher); } @Override public void notifyWatchers(String msg) { for(IWatcher watcher : watchers){ watcher.update(msg); } }}

Watcher:

/** * @author com.tiantian * @version 创建时间:2012-11-20 下午5:04:56 */public class Watcher implements IWatcher{    @Override    public void update(String msg) {        System.out.println(msg);    }}

Test:

/** * @author com.tiantian * @version 创建时间:2012-11-20 下午5:05:26 */public class Test {    public static void main(String[] args) {        IWatched watched = new Watched();        IWatcher watcher1 = new Watcher();        IWatcher watcher2 = new Watcher();        IWatcher watcher3 = new Watcher();        watched.addWatcher(watcher1);        watched.addWatcher(watcher2);        watched.addWatcher(watcher3);        watched.notifyWatchers("I have been clicked!");                watched.removeWatcher(watcher1);        watched.notifyWatchers("what's up");    }}
本文转自天天_byconan博客园博客,原文链接:http://www.cnblogs.com/tiantianbyconan/archive/2012/11/20/2779371.html
,如需转载请自行联系原作者
你可能感兴趣的文章
【Java猫说】Java多线程之内存可见性(下篇)
查看>>
cas工作原理浅析与总结
查看>>
php-socket 客户端/服务端
查看>>
SVN迁移到GIT且保留提交日志
查看>>
cookie、localStorage和sessionStorage详解
查看>>
Python Logging 日志记录入门
查看>>
jenkins+maven+docker+github全自动化部署SpringBoot实例
查看>>
canvas图片绘制跨域问题解决方案Tainted canvases may not be exported
查看>>
Codepen 每日精选(2018-4-28)
查看>>
在Kubernetes上运行高可用的WordPress和MySQL
查看>>
Python 调用 C 动态链接库,包括结构体参数、回调函数等
查看>>
正则表达式速查笔记
查看>>
Go代码打通HTTPs
查看>>
[Leetcode] Reverse Linked List 链表反转(递归与非递归)
查看>>
《SVG精髓》笔记(一)
查看>>
ESP8266_SDK开发基础(1)GPIO输入与输出、软件定时器
查看>>
PHPer面试指南-Laravel 篇
查看>>
HTML中dl元素的高度问题
查看>>
h5单页面布局
查看>>
基础教学 | 什么是负载均衡?
查看>>