java_Observer Design Pattern
摘自:
http://www.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI.html Creating Your Own Event, Source and Listener:
Suppose that we have a source called Light, with two states - on and off. The source is capable of notifying its registered listener(s), whenever its state changes. First, we define the LightEvent class (extends from java.util.EventObject).
Next, we define a LightListener interface to bind the source and its listeners. This interface specifies the signature of the handlers, lightOn(LightEvent) and lightOff(LightEvent).
In the source Light, we use an ArrayList to maintain its listeners, and create two methods: addLightListner(LightListener) and removeLightListener(LightListener). An method called notifyListener() is written to invoke the appropriate handlers of each of its registered listeners, whenever the state of the Light changes.
A listener class called LightWatcher is written, which implements the LightListener interface and provides implementation for the handlers. Event: LightEvent.java
/** LightEvent */
import java.util.EventObject; public class LightEvent extends EventObject {
public LightEvent (Object src) {
super(src);
}
} Listener Interface: LightListener.java
/** The LightListener interface */
import java.util.EventListener; public interface LightListener extends EventListener {
public void lightOn(LightEvent evt); // called-back upon light on
public void lightOff(LightEvent evt); // called-back upon light off
} Source: Light.java
/** The Light Source */
import java.util.*; public class Light {
// Status - on (true) or off (false)
private boolean on;
// Listener list
private List<LightListener> listeners = new ArrayList<LightListener>(); /** Constructor */
public Light() {
on = false;
System.out.println("Light: constructed and off");
} /** Add the given LightListener */
public void addLightListener(LightListener listener) {
listeners.add(listener);
System.out.println("Light: added a listener");
} /** Remove the given LightListener */
public void removeLightListener(LightListener listener) {
listeners.remove(listener);
System.out.println("Light: removed a listener");
} /** Turn on this light */
public void turnOn() {
if (!on) {
on = !on;
System.out.println("Light: turn on");
notifyListener();
}
} /** Turn off this light */
public void turnOff() {
if (on) {
on = !on;
System.out.println("Light: turn off");
notifyListener();
}
} /** Construct an LightEvent and notify all its registered listeners */
private void notifyListener() {
LightEvent evt = new LightEvent(this);
for (LightListener listener : listeners) {
if (on) {
listener.lightOn(evt);
} else {
listener.lightOff(evt);
}
}
}
} Listener: LightWatcher.java
/** An implementation of LightListener class */
public class LightWatcher implements LightListener {
private int id; // ID of this listener /** Constructor */
public LightWatcher(int id) {
this.id = id;
System.out.println("LightWatcher-" + id + ": created");
} /** Implementation of event handlers */
@Override
public void lightOn(LightEvent evt) {
System.out.println("LightWatcher-" + id
+ ": I am notified that light is on");
} @Override
public void lightOff(LightEvent evt) {
System.out.println("LightWatcher-" + id
+ ": I am notified that light is off");
}
} A Test Driver: TestLight.java
/** A Test Driver */
public class TestLight {
public static void main(String[] args) {
Light light = new Light();
LightWatcher lw1 = new LightWatcher(1);
LightWatcher lw2 = new LightWatcher(2);
LightWatcher lw3 = new LightWatcher(3);
light.addLightListener(lw1);
light.addLightListener(lw2);
light.turnOn();
light.addLightListener(lw3);
light.turnOff();
light.removeLightListener(lw1);
light.removeLightListener(lw3);
light.turnOn();
}
} Below are the expected output:
Light: constructed and off
LightWatcher-1: created
LightWatcher-2: created
LightWatcher-3: created
Light: added a listener
Light: added a listener
Light: turn on
LightWatcher-1: I am notified that light is on
LightWatcher-2: I am notified that light is on
Light: added a listener
Light: turn off
LightWatcher-1: I am notified that light is off
LightWatcher-2: I am notified that light is off
LightWatcher-3: I am notified that light is off
Light: removed a listener
Light: removed a listener
Light: turn on
LightWatcher-2: I am notified that light is on
java_Observer Design Pattern的更多相关文章
- 说说设计模式~大话目录(Design Pattern)
回到占占推荐博客索引 设计模式(Design pattern)与其它知识不同,它没有华丽的外表,没有吸引人的工具去实现,它是一种心法,一种内功,如果你希望在软件开发领域有一种新的突破,一个质的飞越,那 ...
- 设计模式(Design Pattern)系列之.NET专题
最近,不是特别忙,重新翻了下设计模式,特地在此记录一下.会不定期更新本系列专题文章. 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结. 使用 ...
- [转]Design Pattern Interview Questions - Part 4
Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...
- [转]Design Pattern Interview Questions - Part 2
Interpeter , Iterator , Mediator , Memento and Observer design patterns. (I) what is Interpreter pat ...
- [转]Design Pattern Interview Questions - Part 3
State, Stratergy, Visitor Adapter and fly weight design pattern from interview perspective. (I) Can ...
- [转]Design Pattern Interview Questions - Part 1
Factory, Abstract factory, prototype pattern (B) What are design patterns? (A) Can you explain facto ...
- design pattern
1. visitor design pattern http://butunclebob.com/ArticleS.UncleBob.IuseVisitor
- Design Pattern: Observer Pattern
1. Brief 一直对Observer Pattern和Pub/Sub Pattern有所混淆,下面打算通过这两篇Blog来梳理这两种模式.若有纰漏请大家指正. 2. Use Case 首先我们来面 ...
- Scalaz(10)- Monad:就是一种函数式编程模式-a design pattern
Monad typeclass不是一种类型,而是一种程序设计模式(design pattern),是泛函编程中最重要的编程概念,因而很多行内人把FP又称为Monadic Programming.这其中 ...
随机推荐
- Google大脑科学家贾杨清(Caffe缔造者)-微信讲座
Google大脑科学家贾杨清(Caffe缔造者)-微信讲座 机器学习Caffe 贾扬清 caffe 一.讲座正文: 大家好!我是贾扬清178,目前在Google Brain69,今天有幸受雷鸣师兄 ...
- sql 跨表修改的方式
update xhj_mon_job_log a set person_id = (select id from xhj_mon_job_manage b where a.task_id = b.id ...
- jQuery 复选框全选/取消全选/反选
jQuery实现的复选框全选/取消全选/反选及获得选择的值. 完整代码: <!DOCTYPE html> <html> <head> <script type ...
- 【Android】4.3 屏幕布局和旋转
分类:C#.Android.VS2015:创建日期:2016-02-06 为了控制屏幕的放置方向(纵向.横向),可以在Resource下同时定义两种不同的布局文件夹:layout和layout-lan ...
- [cocos2dx笔记005]一个字符串管理配置类
在用vs开发cocos2dx过程中.要显示的中文,要求是UTF-8格式的才干正常显示出来.但VS通常是ANSI格式保存,这样,在代码中写入的中文字符串,执行后.显示的就是乱码. 为了正确显示中文.或支 ...
- redis基础之python连接redis(五)
前言 前面介绍了在数据库命令行直接操作redis,现在学习使用python的redis包来操作redis,本人安装的是redis==2.10.6: 系列文章 redis安装和配置 redis命令行操作 ...
- 【Android】自己定义ListView的Adapter报空指针异常解决方法
刚刚使用ViewHolder的方法拉取ListView的数据,可是总会报异常. 细致查看代码.都正确. 后来打开adapter类,发现getView的返回值为null. 即return null. 将 ...
- tomcat 的线程池配置,字符编码设置
优化tomcat配置 ,修改原先的配置 conf/server.xml 配置 <Executor name="tomcatThreadPool" namePrefix=&q ...
- range() 函数详解 python
使用python的人都知道range()函数很方便,今天再用到他的时候发现了很多以前看到过但是忘记的细节.这里记录一下range(),复习下list的slide,最后分析一个好玩儿的冒泡程序. 这里记 ...
- 在mac电脑上写入文件到NTFS格式的移动硬盘的解决办法
需求背景: 今天我在Mac电脑A上下载了11G的资料,想传给Mac电脑B,试用了AirPort.文件共享.远程操作等,传输速度都慢得要死,虽然是在同一个局域网下,两台电脑挨的非常的近,但是还是传得超级 ...