摘自:
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的更多相关文章

  1. 说说设计模式~大话目录(Design Pattern)

    回到占占推荐博客索引 设计模式(Design pattern)与其它知识不同,它没有华丽的外表,没有吸引人的工具去实现,它是一种心法,一种内功,如果你希望在软件开发领域有一种新的突破,一个质的飞越,那 ...

  2. 设计模式(Design Pattern)系列之.NET专题

    最近,不是特别忙,重新翻了下设计模式,特地在此记录一下.会不定期更新本系列专题文章. 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结. 使用 ...

  3. [转]Design Pattern Interview Questions - Part 4

    Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...

  4. [转]Design Pattern Interview Questions - Part 2

    Interpeter , Iterator , Mediator , Memento and Observer design patterns. (I) what is Interpreter pat ...

  5. [转]Design Pattern Interview Questions - Part 3

    State, Stratergy, Visitor Adapter and fly weight design pattern from interview perspective. (I) Can ...

  6. [转]Design Pattern Interview Questions - Part 1

    Factory, Abstract factory, prototype pattern (B) What are design patterns? (A) Can you explain facto ...

  7. design pattern

    1. visitor design pattern http://butunclebob.com/ArticleS.UncleBob.IuseVisitor

  8. Design Pattern: Observer Pattern

    1. Brief 一直对Observer Pattern和Pub/Sub Pattern有所混淆,下面打算通过这两篇Blog来梳理这两种模式.若有纰漏请大家指正. 2. Use Case 首先我们来面 ...

  9. Scalaz(10)- Monad:就是一种函数式编程模式-a design pattern

    Monad typeclass不是一种类型,而是一种程序设计模式(design pattern),是泛函编程中最重要的编程概念,因而很多行内人把FP又称为Monadic Programming.这其中 ...

随机推荐

  1. php 第三方DB库NOTORM

    百度NOTORM找到该库的官网 :http://www.notorm.com/ 打开E:\AppServ\php7\php.ini 找到extension=php_pdo_mysql.dll 解开前面 ...

  2. django 创建数据库表 命令

    一旦你觉得你的模型可能有问题,运行 python manage.py validate . 它可以帮助你捕获一些常见的模型定义错误. 模型确认没问题了,运行下面的命令来生成 CREATE TABLE ...

  3. mysqlbackup 重建带有gtid特性的slave

    一.mysqlbackup简介: mysqlbackup是mysql的一个企业级备份工具,优点就是牛逼,缺点就是这东西要钱买. 二.gtid 特性简介: gtid 的中文名叫全局事务ID,也就是说每一 ...

  4. 【翻译自mos文章】job 不能自己主动执行--这是另外一个mos文章,本文章有13个解决方法

    job 不能自己主动执行--这是另外一个mos文章 參考原文: Jobs Not Executing Automatically (Doc ID 313102.1) 适用于: Oracle Datab ...

  5. jQuery $.extend()使用方法

    $.extend()使用方法总结. jQuery为开发插件提拱了两个方法,各自是: jQuery.fn.extend(object); jQuery.extend(object); jQuery.ex ...

  6. Spring 一二事(10) - annotation AOP

    先贴出POM的内容,这个毕竟是用的maven来简单构建的 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:x ...

  7. DPDK

    Intel DPDK 全面解读   高性能网络技术 随着云计算产业的异军突起,网络技术的不断创新,越来越多的网络设备基础架构逐步向基于通用处理器平台的架构方向融合,从传统的物理网络到虚拟网络,从扁平化 ...

  8. jvisualvm工具使用

    VisualVM 是Netbeans的profile子项目,已在JDK6.0 update 7 中自带(java启动时不需要特定参数,监控工具在bin/jvisualvm.exe). https:// ...

  9. JS页面跳转并及时刷新

    "<script type='text/javascript'>alert('操作成功!');window.history.go(-2);window.close();</ ...

  10. C++虚函数表与虚析构函数

    1.静态联编和动态联编联编:将源代码中的函数调用解释为要执行函数代码. 静态联编:编译时能确定唯一函数.在C中,每个函数名都能确定唯一的函数代码.在C++中,因为有函数重载,编译器须根据函数名,参数才 ...