观察者模式
来源:互联网 发布:龙虎榜持仓数据变化 编辑:程序博客网 时间:2024/05/18 02:41
首先从结构上认识观察者模式:
4、QQConnection对自定义的监听进行保存
5、最后在QQFrame中组装起来
1、抽象主题角色
主题角色把所有对观察者对象的引用保存在 一个容器里,每个主题可以有任何数量的观察者。
2、抽象观察者角色
为所有的具体观察者定义一个接口,得到主题的通知时更新自己。
3、具体主题角色
将有关对象存入具体观察者对象;在具体主题内部改变时,给所有登记过的观察者发出通知。
4、具体观察者角色
存入与主题状态自适的状态。
java用到观察者模式的地方,主要是监听器那一块,监听器是事件和事件源的中间部分,要对相应的事件进行
处理。
自定义监听里面实现观察者模式的使用
1、QQListener接口
public interface QQListener{void onSendMsg(Message msg);}
2、QQTree实现
public class QQTree extends JTree implements QQListener {DefaultMutableTreeNode root = new DefaultMutableTreeNode("信息列表");public QQTree() {TreeModel model = new DefaultTreeModel(root);this.setModel(model);}public void onSendMsg(Message msg) {DefaultMutableTreeNode node = new DefaultMutableTreeNode(msg.toString());root.add(node);// 刷新javax.swing.SwingUtilities.updateComponentTreeUI(this);<span style="white-space:pre"></span> }}3、QQButton实现
public class QQButton extends JButton implements QQListener{public QQButton(String text){super(text);}@Overridepublic void onMsg(Message msg) {this.setText(msg.toString());msg.setContent("QQButton 改变了内容。。。");}}
4、QQConnection对自定义的监听进行保存
public class QQConnection extends Thread {List<QQListener> list = new ArrayList<QQListener>();public void addMsgListener(QQListener listener) {list.add(listener);}public void run() {int count = 0;while (true) {count++;try {sleep(1000);} catch (Exception e) {e.printStackTrace();}String content = "消息到达!" + count;Message msg = new Message(count, content);// 对消息进行分发操作(取出所有的监听器对象处理消息)for (QQListener qqListener : list) {qqListener.onSendMsg(msg);}}}}
5、最后在QQFrame中组装起来
public class QQFrame extends JFrame {public void showFrame() {this.setTitle("观察者模式");this.setLayout(new FlowLayout());this.setDefaultCloseOperation(3);this.setLocationRelativeTo(null);this.setSize(400, 600);QQTree tree = new QQTree();add(tree);//模拟启动通信模块QQConnection conn = new QQConnection();conn.start();//给通信模块添加消息处理时间conn.addMsgListener(tree);this.setVisible(true);}}
0 0
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- CSDN
- 荀子 《劝学》
- Hashtable和HashMap的区别
- 解压web服务器返回的gzip数据
- 2013山东省赛Rubik’s cube 魔方BFS
- 观察者模式
- 传感器和Android平台的开放性结合在一起-传感器之家文章 - 传感器知识博客 - yuyangsensor - 和讯博客
- String类的概述和使用
- android apk 防止反编译技术第三篇-加密apk
- alias 添加
- 第六周项目六--复数模板类(友元函数)
- 零基础入门学习C 001
- html5 websocket 无法建立到服务器的连接 一种解决方法
- thinking in java第七天